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

20,897

Solution 1

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.

Solution 2

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;
Share:
20,897
Ariful Haque
Author by

Ariful Haque

Backend Software Engineer at Trivago. In my free time, I work on LaptopList.com. My Daily Tools Backend: Laravel, CakePHP, PHP7 Frontend: ReactJs, JavaScript (ES6), jQuery, Ajax Database: MySQL, Build: Webpack, Grunt Server: Ubuntu, CentOS, DigitalOcean, Google Cloud, AWS Development Environment: PHPStorm, VSCode, Docker, Kubernetes, Vagrant Version Control: Git, Github

Updated on July 09, 2022

Comments

  • Ariful Haque
    Ariful Haque almost 2 years

    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.