在 Laravel Controller 中,如果所有函数都使用 Request,那么直接在构造函数而不是函数中注入(inject) Request 是否正确?
下面的代码有效,我只是想知道它是否正确以及它是否有副作用...
class BananaController extends Controller
{
protected $request; // request as an attribute of the controllers
public function __construct(Request $request)
{
$this->middleware('auth');
$this->request = $request; // Request becomes available for all the controller functions that call $this->request
}
public function store()
{
$this->validate($this->request, [
'text' => 'required',
]);
// I save the banana attributes and the controller continues...
放轻松,关于 stackoverflow 的第一个问题 :-)
[附录] 明确地说,“常规”代码是:
class BananaController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request)
{
$this->validate($request, [
'text' => 'required',
]);
// I save the banana attributes and the controller continues...
最佳答案
我一直在使用相同的技术通过请求保护我的所有资源 Controller 路由(例如检查登录用户是否有权访问该资源)
但是,从 Laravel 5.3 开始, Controller 构造函数现在在中间件执行之前运行,它实际上破坏了请求中的路由模型绑定(bind)。
因此,如果您将请求直接注入(inject)到 Controller 方法中,就像在 Laravel 文档中一样,并且如果您有任何绑定(bind)到路由的模型,它会很好地解决它,但是如果您在 Controller 构造函数中注入(inject)请求并尝试访问您的请求中的模型如下所示 - 它将仅返回资源 ID 而不是模型。
//Route service provider
Route::model('resource', MyModel::class);
//Request class
public function authorize()
{
//We expect to get a resource or null
//But now it just returns the resource id
if (!is_null($this->resource))
{
return $this->resource->createdBy->id == $this->getLoggedUser()->id;
}
}
关于php - Laravel 请求 : it's correct injecting Request directly in the controller constructor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38998282/