Access @store arguments in “create policy”

♀尐吖头ヾ 提交于 2019-12-13 17:34:19

问题


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');

});

We see here that it has implicit {pet}.

My controller accesses {pet} just fine like this:

app\Http\Controllers\MessageController.php:

public function store(Request $request, Pet $pet)
{
    dd($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?

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');
}

Also dd is not working for some reason.


回答1:


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.

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

Again, some actions like create may not require a model instance. In these situations, you may pass a class name to the middleware. The class name will be used to determine which policy to use when authorizing the action


So in your case :

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

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

});

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

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



回答2:


You could use the request() helper method.

https://laravel.com/docs/5.5/helpers#method-request




回答3:


The $request have a method has() for determining if a value is present (Link). You can alter your method to check if the value exists or its equals to "PLAIN"

public function create(User $user, Request $request)
{
    return !$request->has('kind') || $request->input('kind') == 'PLAIN';
}



回答4:


use

return ( $request->has('kind') )? $request->has('kind') && $request->input('kind') === 'PLAIN': true;


来源:https://stackoverflow.com/questions/46777395/access-store-arguments-in-create-policy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!