Showing posts with label Laravel5. Show all posts
Showing posts with label Laravel5. Show all posts

Saturday, March 3, 2018

[Resolved] Laravel fresh install index page shows 500 internal server error, no error log

I am using Laravel 5.6 with php7.2 version, I ensure I have removed the old php modules and these extension are with status enabled in my server:
PHP >= 7.1.3
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
XML PHP Extension
Ctype PHP Extension
JSON PHP Extension
Remark :
Remember you must ensure your php version is bigger or equal to version 7.1.3
It's strange that check server error log found nothing...

What I do is remove the whole laravel 5.6 project and install it again,
found there is some problem during installed :
    Error message : PHP extension dom is missing from you system.

What to do is install this php-do, here is the example using yum here:
sudo yum install php-dom
After you installed the missing extensions and run the command install laravel 5.6 again,
you may find the problem is alright .
sudo composer create-project --prefer-dist laravel/laravel blog

Reference 
https://laravel.com/docs/5.6

Saturday, September 9, 2017

[Laravel 5.5][Resoled] Call to undefined method Tests\Feature\AlphaTest::visit()


Error Message

PHPUnit 6.4.4 by Sebastian Bergmann and contributors.

E...                                                                4 / 4 (100%


Time: 200 ms, Memory: 10.00MB
There was 1 error:
1) Tests\Feature\AlphaTest::testDisplaysAlpha
Error: Call to undefined method Tests\Feature\AlphaTest::visit()
C:\wxxx\www\testxxxxxxxxx\tests\Feature\AlphaTest.php:18
ERRORS!
Tests: 4, Assertions: 9, Errors: 1.
And here is the test case source code :
<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class AlphaTest extends TestCase
{
    public function testDisplaysAlpha()
    {
        $this->assertTrue(true);
        $this->visit('/alpha')
             ->see('Alpha')
             ->dontSee('Beta');
    }
}

There is no visit method built-in by default in Laravel 5.5. It uses dusk to perform browser tests and the method visit() is not available anymore. If you still wanted to use those behavior, install laravel/browser-kit-testing package :
composer require laravel/browser-kit-testing --dev
More reference  about browser-kit-testing reference this:
https://github.com/laravel/browser-kit-testing#laravel-browserkit-testing

After finished installing laravel/browser-kit-testing package to your laravel 5.5 project , edit your \test\TestCase.php from the default one to this:
<?php

namespace Tests;

//use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Laravel\BrowserKitTesting\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
    public $baseUrl = 'http://localhost';
}
What we need to do is import Laravel\BrowserKitTesting\TestCase as BaseTestCase instead of Illuminate\Foundation\Testing\TestCase as BaseTestCase; and then default a value named $baseUrl.

Run your test again :

Since this is the old method, it's recommend to learn using another alternative : Laravel Dusk to run full browser tests

Reference

https://laracasts.com/discuss/channels/testing/call-to-undefined-method-viewtransactionlisttestvisit
https://stackoverflow.com/questions/42645066/acceptance-test-method-visit-undefinied
https://laravel.com/docs/5.5/dusk

Thursday, August 10, 2017

[Laravel5.5][Dusk][Resolved] Default ExampleTest return Did not see expected text [Laravel] within element [body] message


Error message :
C:\wamp\www\exampleapp>php artisan dusk
Warning: TTY mode is not supported on Windows platform.
PHPUnit 6.4.4 by Sebastian Bergmann and contributors.
[1110/163504.684:ERROR:devtools_http_handler.cc(786)]
DevTools listening on 127.0.0.1:12327
F                                                                   1 / 1 (100%)
Time: 25.15 seconds, Memory: 12.00MB
There was 1 failure:
1) Tests\Browser\ExampleTest::testBasicExample
Did not see expected text [La] within element [body].
Failed asserting that false is true.
C:\wamp\www\exampleapp\vendor\laravel\dusk\src\Concerns\MakesAssertions.php:2
74
C:\wamp\www\texampleapp\vendor\laravel\dusk\src\Concerns\MakesAssertions.php:2
45
C:\wamp\www\exampleapp\tests\Browser\ExampleTest.php:22
C:\wamp\www\exampleapp\vendor\laravel\dusk\src\TestCase.php:92
C:\wamp\www\exampleapp\tests\Browser\ExampleTest.php:23

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

Source code:

ExampleTest.php
<?php

namespace Tests\Browser;

use Tests\DuskTestCase;
use Laravel\Dusk\Browser;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class ExampleTest extends DuskTestCase
{
    /**
     * A basic browser test example.
     *
     * @return void
     */
public function testBasicExample()
{
    $this->browse(function ($browser) {
        $browser->visit('/')
            ->assertSee('Laravel');
    });
}
}

Solution

I found amend the APP_URL value in .env file can solve the problem. For example, if application url to view your root page is this :
http://localhost/exampleapp/public/

and then your APP_URL value in .env should be http://localhost/testcaseapp/public :



Perform the test again:


Reference

https://laravel.com/docs/5.5/dusk

Wednesday, July 26, 2017

[Laravel 5.5][Resolved] Class url not found in view

Have you move the view code from old laravel version?
Check have you missed to change old syntax, and are u using deprecated syntax.
for example, change this from
url::to("images/abc.jpg");
to
url("images/abc.jpg");

Saturday, July 22, 2017

[Laravel5.5][Resolved] Argument 1 passed to ForgotPasswordController::sendResetLinkFailedResponse() must be an instance of App\Http\Controllers\Auth\Request

Error message

Type error: Argument 1 passed to App\Http\Controllers\Auth\ForgotPasswordController::sendResetLinkFailedResponse()
must be an instance of App\Http\Controllers\Auth\Request,
instance of Illuminate\Http\Request given,
called in /var/www/example.com/public_html/vendor/laravel/framework/src/Illuminate/Foundation/Auth/SendsPasswordResetEmails.php on line 39

Solution

replace use "use App\Http\Requests;" by "use Illuminate\Http\Request;".

Reference

https://laracasts.com/discuss/channels/general-discussion/class-apphttpcontrollersrequest-does-not-exist?page=1

Tuesday, July 4, 2017

[laravel5.5][Resolved] laravel yield in php

 In blade template, it's :

@yield("title")
In php code, it's : (text in green)
<?php echo View::getSection('title'); ?>

Reference:
https://laravel.com/docs/5.5/blade
https://stackoverflow.com/questions/47847610/laravel-yield-in-code-php

Monday, July 3, 2017

[Laraval5.4][Resolved] php artisan migrate [Illuminate\Database\QueryException] No such file or directory (SQL: select * from inform ation_schema.tables where table_schema = xxxxxxxx


Error message

 [Illuminate\Database\QueryException]
  SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from inform
  ation_schema.tables where table_schema = xxxxxxxx and table_name = migrat
  ions)
  [PDOException]
  SQLSTATE[HY000] [2002] No such file or directory

Solution

What to do is your find out your unix_socket location first and then amend your config/database.php file:

Follow the link below to find out your unix_socket first, what i get is "/var/lib/mysql/mysql.sock"
[mysql][Resolved] find out your unix socket

Open your config/database.php file and place the path as value of unix_socket :


and then run your "php artisan migrate" again.

Reference

https://stackoverflow.com/questions/19475762/setting-up-laravel-on-a-mac-php-artisan-migrate-error-no-such-file-or-directory

Wednesday, June 21, 2017

[Laravel 5.4][Resolved] QueryException SQLSTATE[42000]: Syntax error or access violation: 1055

What i did is update laravel version from 5.0 to 5.4, found everything works but this sql by query builder.:



By default laravel 5.4 would select all (SELECT * ) if you haven't specific the column name you wanted to select, it causes error.

Solution 1

What you can do is add the column name caused error to your groupBy part:
From :
$data   = DB::table('table_a')->where('userid','=', Auth::user()->id)
                            ->where('species','!=', '')
                            ->where('action','=', 'insert')
                            ->join('table_b', 'table_b.index_id', '=', 'table_a.species')
                            ->join('table_c', 'table_b.table_c', '=', 'table_c.name_id')
                            ->groupBy('table_a.species')
                            ->take(5)->orderBy('table_b.last_edit_timestamp', 'desc')->get();
To
$data  = DB::table('table_a')->where('userid','=', Auth::user()->id)
                            ->where('species','!=', '')
                            ->where('action','=', 'insert')
                            ->join('table_b', 'table_b.index_id', '=', 'table_a.species')
                            ->join('table_c', 'table_b.table_c', '=', 'table_c.name_id')                            ->groupBy('table_a.species','table_b.last_edit_timestamp',"scientific_name","formatted_sciname")
                            ->take(5)->orderBy('table_b.last_edit_timestamp', 'desc')
                            ->select(["scientific_name","formatted_sciname","species"])
                            ->get();

Solution 2 

change default value of strict from true to false, in config/database.php at "mysql"
 'strict' => true


Reference :

https://github.com/barryvdh/laravel-translation-manager/issues/144

Monday, May 15, 2017

[Laravel5] Route : Attribute [controllers] does not exist.


Error message

InvalidArgumentException in RouteRegistrar.php line 75:
Attribute [controllers] does not exist.

Source Code: 

Route::controllers([
    'lists' => 'ListsController',
    'tasks' => 'TasksController',
]);

Reason

Route::controllers method (Implicit controller) defining series of URIs and associated controllers, reflection is used parse and register all of the controller’s routable methods. However, this controller method in route is deprecated since 5.2 (or 5.3, i can't sure) but it works at 5.1 (according to user: SaeedPrez at https://laracasts.com/discuss/ and RïshïKêsh Kümar ay https://stackoverflow.com),  check your laravel version.


Method 1

You can use this laravel routes publisher package to replace deprecated Route::controller() and Route::controllers() with explicit routes:
https://github.com/themsaid/laravel-routes-publisher.

Method 2

You can use the resource method (RESTful Resource controller) which get similar purpose with controller method (Implicit controller):

https://stackoverflow.com/questions/23505875/laravel-routeresource-vs-routecontroller

Example code

Using Route::resource method:
Route::resource('lists','ListsController');
Route::resource('tasks','TasksController');
but you also need to change the controllers method name such as something like:

From :
<?php namespace example\Http\Controllers;
   
    class ListsController extends Controller {

        public function getIndex()
        {
            return view('lists.index');
        }

        public function getCreate()
        {
            return view('lists.create');
        }
       
        public function postStore()
        {
            return view('lists.store')
        }
    }
?>
To:
<?php namespace example\Http\Controllers;
    class ListsController extends BaseController {

    public function index() {
        return view('lists.index');
    }

    public function create()
    {
        return view('lists.create');
    }

    public function store()
    {
        return view('lists.store')
    }

}
For detail of RESTful Resource controller and Implicit controller, you can reference from the answer at stackoverflow.com by RyanWinchester :
https://stackoverflow.com/questions/23505875/laravel-routeresource-vs-routecontroller 
and resource controller doc with laravel 5.4 :
https://laravel.com/docs/5.4/controllers#resource-controllers

Reference

https://laracasts.com/discuss/channels/laravel/implicit-controllers-laravel-54
https://laracasts.com/discuss/channels/laravel/routecontrollers-in-laravel-54
https://stackoverflow.com/questions/43572635/php-laravel-attribute-controller-does-not-exist

Thursday, May 11, 2017

[Lavarel 5.4][LogicException] Unable to prepare route [api/user] for serialization. Uses Closure

Error message

LogicException Unable to prepare route [api/user] for serialization. Uses Closure

I can't sure is the error solved but used a method to except from the problem.
Check your routes/api.php file existed , don't delete it:


Open the file and comment or remove these 3 lines:


cache the routes again and success:


Reference

https://laracasts.com/discuss/channels/laravel/makeauth-causes-unable-to-prepare-route-apiuser-for-serialization-uses-closure

Thursday, April 13, 2017

[Laravel5][Resolved] BadMethodCallException Method locate does not exist.

I used Lang::locate() to get current message but failed, it's the error message:
(1/1) BadMethodCallException
Method locate does not exist.
in Macroable.php (line 74)
at Translator->__call('locate', array())
in Facade.php (line 221)
at Facade::__callStatic('locate', array())
Example code:
use Lang;
class OrderService
{
    protected $lang;
  
    public function __construct() {
        $this->lang = Lang::locate();
    }
} 
Since there is a bit strange and i almost can't find anyone with this strange case on internet,
using "Config::get('app.locale');" to replace Lang::locate(); works.

use Config;
 class OrderService
{
    protected $lang;
  
    public function __construct() {
        $this->lang = Config::get('app.locale');
    }
}

Reference

https://stackoverflow.com/questions/12706463/how-can-i-find-the-current-language-in-a-laravel-view

Wednesday, March 29, 2017

[Laravel 5.4][Resolved] Foreign key constraint is incorrectly formed


 Error message:
 [Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1005 Can't create table `mhhk`.`#sql-1b24_2  b` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter   table `news` add constraint `news_user_id_foreign` foreign key (`user_id`)   references `users` (`user_id`) on delete cascade)          

Firstly, you need to ensure you create the foreign key column, such as :
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade');
And then you should ensure the table and column you referenced to is created. For example, the schema builder with foreign() column type show above would create this sql :
ALTER TABLE `news` add constraint `news_user_id_foreign` foreign key(`user_id`) references 'users' (`user_id`) on delete cascade
In this case, it add a constraint named `news_user_id_foreign` to table `news`, it makes existing column `user_id` in table `news` references to column `user_id` in table `users`. To run this sql statement successfully, you need to ensure the table `users` and column `user_id` exists. It's better if make that column unique. An example :

$table->increments('user_id')->unique();
Also please ensure foreign key and column reference from foreign key are with same data type.

Do migration again. if it's still not work, reset migrate and then run dump-autoload via command prompt:
php artisan migrate:reset
composer dump-autoload

Reference

https://stackoverflow.com/questions/22367088/laravel-foreign-key-constraint-is-incorrectly-formed 
https://stackoverflow.com/questions/43103692/eloquent-foreign-key-constraint-is-incorrectly-formed-laravel

Tuesday, March 28, 2017

[Laravel 5][Resolved] syntax error or access violation: key column doesn't exists in table



Error message :
[PDOException]
SQLSTATE[42000] : Syntax error or access violation: 1072 key column 'key_id' doesn't exists in table
The error caused by you missed creating the column "key_id" before you assign it as foreign key.

There is the example with problem:
Schema::create('tables', function (Blueprint $table) {
    $table->increments('d')->uniqlue();
    $table->foreign('key_id',10)->references('news_id')->on('news')->nullable();
    $table->string('title',30)->nullable();
    $table->timestamps();
    $table->softDeletes();
});
Corrected code:
Schema::create('tables', function (Blueprint $table) {
    $table->increments('d')->uniqlue();
    $table->integer('key_id')->unsigned()->nullable();
    $table->foreign('key_id',10)->references('news_id')->on('news')->nullable();
    $table->string('title',30)->nullable();
    $table->timestamps();
    $table->softDeletes();
});

Reference

https://stackoverflow.com/questions/33633684/laravel-migration-cant-add-foreign-key

Thursday, March 23, 2017

[Laravel 5.4] syntax error or access violation: 1071 Specified key was too long: max key length is 767 bytes

Error message :
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes.
Visit the AppServiceProvider.php file in your project : \app\Providers\AppServiceProvider.php

C:\wamp\htdocs\m\app\Providers\AppServiceProvider.php


and this line within boot() function
Schema::defaultStringLength(191);

and this line under namespace:
use Illuminate\Support\Facades\Schema;

Example code :

Reference

https://github.com/laravel/framework/issues/17508

Tuesday, February 14, 2017

[Laravel5.4][Resolved] array_merge(): Argument #2 is not an array

(2/2) ErrorException

array_merge(): Argument #2 is not an array (View: C:\xampp\htdocs\test\resources\views\articles\show.blade.php)
in Factory.php (line 134)
at CompilerEngine->handleViewException(object(ErrorException), 1)in PhpEngine.php (line 44)
I think there maybe many reason to cause this problem, I almost can't search the solution from internet to solve this...
Finally I found this line cause the problem, where the $data is an object:
@include('modules.panel', $data)
I guess this require argument two as array format but it's an object, so i convert it to array and it works fine:
@include('modules.panel', (array) $data)

Thursday, January 19, 2017

[Laravel 5][Resolved] patch update MethodNotAllowedHttpException

Got an error message :
(1/1)MethodNotAllowedHttpException

in RouteCollection.php (line 251)

at RouteCollection->methodNotAllowed(array('PATCH', 'DELETE'))
in RouteCollection.php (line 238)

at RouteCollection->getRouteForMethods(object(Request),array('PATCH', 'DELETE'))
in RouteCollection.php (line 176)

at RouteCollection->match(object(Request))
in Router.php (line 548)

at Router->findRoute(object(Request))
in Router.php (line 527)

at Router->dispatchToRoute(object(Request))
in Router.php (line 513)

at Router->dispatch(object(Request))
in Kernel.php (line 176)

at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))

It cause by sending a post request to a path but the target page register as HTTP verb PATCH in routes file.

html :

<form method="POST" action="http://localhost:1234/test/item/2" accept-charset="UTF-8" class="form-horizontal">

route file (\test\routes\web.php)

Route::patch ('item/{id}','TestController@update')->name('test.update');


Solution

Method 1 :

Add this line to your form, input type "hidden" with input name "_method" and value "PATCH":

<input name="_method" type="hidden" value="PATCH">
Method 2 :
If you use model binding , define your method as PATCH
Form::model($test ,["route"=>url("item/".$id) ,"method"=>"PATCH"])
So that form elements it would auto add a "<input name="_method" type="hidden" value="PATCH">" sentence after your opening tag of your form element.

Reference

https://stackoverflow.com/questions/25857650/laravel-form-wont-patch-only-post-nested-restfull-controllers-methodnotallo

Sunday, January 1, 2017

[Laravel][Resolved] Call to undefined method PHPUnit_Util_Configuration::getTestdoxFroupConfigturation() in ..


2 things can do, 
firstly, update your composer by this command first:
composer update
And then use your phpunit command to check it work or not , if still fail, use another command to run your unit test:
YOUR_PROHECT_DIRECTORY\vendor\bin\phpunit
Change text YOUR_PROHECT_DIRECTORY in red to your directory path, for my case the project is named demo :
C:\xampp\htdocs\demo\vendor\bin\phpunit

Reference

https://stackoverflow.com/questions/41868027/phpunit-uncaught-error-call-to-undefined-method-phpunit-util-configurationget

Saturday, December 3, 2016

[Laravel5] index page won't apply middleware on route

The case is about i created a middleware and it works at each page but not the index page, it should make redirection but it shows 404 error when visited.

PROJECT_ROOT\routes\web.php
Route::get   ('/', 'PageController@home');
Firstly, you should  run the command "composer dump-autoload" first and then refresh webpage, check if the problem still exists
composer dump-autoload

If the problem still here, visit your Kernel file (located at PROJECT_ROOT\app\Http\Kernel.php), check have you added your path of middleware to $middleware:


For my case, i missed register that middleware so it's doesn't work, it alright now.

Reference

https://stackoverflow.com/questions/31418662/laravels-middleware-not-working-on-controller

Sunday, October 9, 2016

[OAuth2][Laravel][Resolved] your requirements could not be resolved to an installable set of packages

Problem

My story is i am following a tutorial and tried to install OAuth2 package with composer for laravel5.0 but fail, this is the part i added in composer.json located in project root.
    "require": {
        "laravel/framework": "5.0.*",
        "lucadegasperi/oauth2-server-laravel": "5.0.*"
    },

the related command on Windows platform :
composer update
And the error message :
your requirements could not be resolved to an installable set of packages: Conclusion: don't install laravel/frameworkv5.0.xx

Solution

Firstly you have to visit official OAuth2 package website to check are you required to install a correct OAuth2 package version via composer
Official site of github lucadegasperi/oauth2-server-laravel :
https://github.com/lucadegasperi/oauth2-server-laravel

For my case i should install "lucadegasperi/oauth2-server-laravel": "4.0.*" but not "lucadegasperi/oauth2-server-laravel": "5.0.*" for my laravel 5.0.x.

So i have to correct the oauth2 version and run "composer update" command again.

    "require": {
        "laravel/framework": "5.0.*",
        "lucadegasperi/oauth2-server-laravel": "4.0.*"
    },



Saturday, May 7, 2016

[Laravel5][Resolved] Error include_path='. /usr/share/pear /usr/share/php'

Version : Laravel 5.0
OS : CentOS 7 

source :
<?php
namespace App\Http\Controllers;

use Mail;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use LibsName\LibsName;

class ClassName extends Controller
{

    public function sendXxxxXxxxx(Request $request)
    {
        require 'App/Libraries/LibsName/vendor/autoload.php'; //error from this line
        echo "hello!!! ";
    }
}
?>
Value after the word "require" is path of php file, it's case sensitive. After i corrected the value from 'App/Libraries/LibsName/vendor/autoload.php'; to 'app/Libraries/LibsName/vendor/autoload.php'; , the application able to load the require file and then problem solved.

    public function sendXxxxXxxxx(Request $request)
    {
        require 'app/Libraries/LibsName/vendor/autoload.php'; //error from this line
        echo "hello!!! ";
    }

Reference:

http://stackoverflow.com/questions/23186952/error-in-exception-handler-laravel
http://php.net/manual/en/function.require.php