Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class 'App\Http\Controllers\Artisan' not found in Laravel 5

I am in new Laravel and trying to learn by coding. I created migration and seed and both working fine when I call them from terminal, but I wanted to try this code in my HomeController and I get a big error.

Error

FatalErrorException in HomeController.php line 23: 
Class 'App\Http\Controllers\Artisan' not found

Code in Home Controller

$hasTable = Schema::hasTable('users');      

if ($hasTable==0)
        {
            echo "call cli to migration and seed";

            $migrate = Artisan::call('migrate');
            $seed = Artisan::call('db:seed');

            echo "Migrate<br>";

            print_r($migrate);
            echo "Seed<br>";
            print_r($seed);
        }

I believe, if I load the correct namespace, I can avoid this error, but I am not sure.

like image 360
Ariful Haque Avatar asked May 03 '15 10:05

Ariful Haque


2 Answers

Assuming you have the default Artisan alias set in your config/app.php, you're right that you just need to import the correct namespace.

Either add this top of the file:

use Artisan;

Or use a fully qualified namespace in your code:

$migrate = \Artisan::call('migrate');

If you don't have the alias set for whatever reason, use

use Illuminate\Support\Facades\Artisan;

instead.

like image 68
Clive Avatar answered Sep 23 '22 23:09

Clive


When you just reference a class like Artisan::call('db:seed') PHP searches for the class in your current namespace.

In this case that's App\Http\Controllers. However the Artisan class obviously doesn't exists in your namespace for controllers but rather in the Laravel framework namespace. It has also an alias that's in the global namespace.

You can either reference the alias in the root namespace by prepending a backslash:

return \Artisan::call('db:seed');

Or add an import statement at the top:

use Artisan;
like image 29
Limon Monte Avatar answered Sep 25 '22 23:09

Limon Monte