本文介绍了在“创建策略"中访问@store参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在routes/api.php中有一条这样的路线:

I have a route like this in routes/api.php:

Route::group(['middleware' => 'auth:api'], function() {

    Route::post('messages/{pet}', 'MessageController@store')->middleware('can:create,message');

});

我们在这里看到它具有隐式{pet}.

We see here that it has implicit {pet}.

我的控制器访问{pet}就像这样:

My controller accesses {pet} just fine like this:

app\Http\Controllers\MessageController.php:

public function store(Request $request, Pet $pet)
{
    dd($pet);
}

我想让我的->middleware('can:create,message')在这里看到store的参数,所以我想要$request$pet,这可能吗?

I want to my ->middleware('can:create,message') to get the arguments of store seen here, so I want $request and $pet, is this possible?

这是我当前的MessagePolicy@create,但是没有得到我期望的参数:

Here is my current MessagePolicy@create but its not getting the arguments I expect:

app\Policies\MessagePolicy.php

public function create(User $user, Request $request, Pet $pet)
{
    dd($request); // dd($pet);
    return $user->can('view', $pet) && ($request->input('kind') == null|| $request->input('kind') == 'PLAIN');
}

dd出于某种原因也无法正常工作.

Also dd is not working for some reason.

推荐答案

假设您要为给定消息创建Pet,在这种情况下,为隐式模型绑定在这里不起作用,因为尚未创建宠物,因此按给定ID查找宠物将始终返回null.

Assuming you want create a Pet for a given message, in this case the implicit model binding will not work here because the pet not yet created so finding a pet by the given id will always return null.

在这种情况下,laravel提供了使用不需要模型的操作的可能性(请参阅文档->通过中间件部分)

In this case laravel offer the possibility to use Actions That Don't Require Models (see documentation -> Via Middleware section)


所以在您的情况下:


So in your case :

Route::group(['middleware' => 'auth:api'], function() {

    Route::post('messages/{pet}', 'MessageController@store')->middleware('can:create,App\Pet');

});

PetPolicy 中,您可以使用request()帮助方法:

And in the PetPolicy you can use the request() helper method :

public function create(User $user)
{
    return request('kind') == null|| request('kind') == 'PLAIN';
}

这篇关于在“创建策略"中访问@store参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 18:27