Search code examples
phplaravelnamespaceslaravel-5laravel-artisan

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.


Solution

  • 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.