在 Laravel 5 中找不到类“App\Http\Controllers\Artisan”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30012946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Class 'App\Http\Controllers\Artisan' not found in Laravel 5
提问by Ariful Haque
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.
我在新的 Laravel 中并尝试通过编码来学习。我创建了迁移和种子,当我从终端调用它们时,它们都可以正常工作,但是我想在我的 HomeController 中尝试这段代码,但出现了一个大错误。
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.
我相信,如果我加载了正确的命名空间,我可以避免这个错误,但我不确定。
回答by Clive
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.
假设您Artisan
在 config/app.php 中设置了默认别名,那么您只需要导入正确的命名空间就对了。
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.
反而。
回答by Limon Monte
When you just reference a class like Artisan::call('db:seed')
PHP searches for the class in your current namespace.
当您只引用像Artisan::call('db:seed')
PHP这样的类时,会在您当前的命名空间中搜索该类。
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 globalnamespace.
在这种情况下,就是App\Http\Controllers
. 但是,Artisan
该类显然不存在于控制器的命名空间中,而是存在于 Laravel 框架命名空间中。它还有一个位于全局命名空间中的别名。
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;