路由到Laravel 8中的控制器 [英] Route to controller in Laravel 8
问题描述
我正在使用Laravel 8,当我将路由写到 __ invoke
控制器时是这样的:
I'm working with Laravel 8 and when I write the route to the __invoke
controller like this:
use App\Http\Controllers\PortfolioController;
Route::get('/portfolio', 'PortfolioController')->name('portfolio');
它显示此错误:
无效的路由操作:[PortfolioController].
PortfolioController
不可调用
所以它只能这样工作:
Route::get('/portfolio', [PortfolioController::class, '__invoke'])->name('portfolio');;
这对我没有意义,因为它应该找到 __ invoke
,这是 PortfolioController.php
中唯一的一个:
Which doesn't make sense to me because it should find the __invoke
which is the only one in PortfolioController.php
:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PortfolioController extends Controller
{
/**
* Handle the incoming request.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function __invoke(Request $request)
{
$portfolio = [
['title' => 'Project #1'],
['title' => 'Project #2'],
['title' => 'Project #3'],
['title' => 'Project #4'],
];
return view('portfolio',compact('portfolio'));
}
}
Laravel 8是否忽略了 __ invoke
属性?
Is Laravel 8 ignoring the __invoke
attribute???
推荐答案
TL; DR
这样做:
use App\Http\Controllers\PortfolioController;
Route::get('/portfolio', PortfolioController::class)->name('portfolio');
^^^^^^^^^^^^^^^^^^^^^^^^^^
说明
在Laravel 8之前,路由是在 RouteServiceProvider.php
中命名的:
protected $namespace = 'App\Http\Controllers';
// ...
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace) // <----
->group(base_path('routes/web.php'));
}
因此,当您定义路线时,例如您的示例:
So, when you defined routes, like in your example:
Route::get('/portfolio', 'PortfolioController')->name('portfolio');
^^^^^^^^^^^^^^^^^^^^^
PortfolioController
字符串已使用 App \ Http \ Controllers
命名空间.
The PortfolioController
string were namespaced with App\Http\Controllers
.
在Laravel 8中,此行为已被修改.从 v8发行说明:
In Laravel 8 this behavior has been modified. From the v8 release note:
在Laravel 8.x中,此属性默认为
null
.这意味着没有自动命名空间前缀将由Laravel完成.因此,在新的Laravel 8.x应用程序,控制器路由定义应为使用标准PHP可调用语法定义:
In Laravel 8.x, this property is
null
by default. This means that no automatic namespace prefixing will be done by Laravel. Therefore, in new Laravel 8.x applications, controller route definitions should be defined using standard PHP callable syntax:
use App\Http\Controllers\UserController;
Route::get('/users', [UserController::class, 'index']);
现在,对于您提到的特殊情况, __ invoke()
方法,这就是您应该如何处理它们
Now, for the particular case you mentioned, __invoke()
methods, this is how you should handle them according to the docs:
为单个动作控制器注册路由时,不需要指定方法:
When registering routes for single action controllers, you do not need to specify a method:
use App\Http\Controllers\ShowProfile;
Route::get('user/{id}', ShowProfile::class);
这篇关于路由到Laravel 8中的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!