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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With