我正在尝试为不起作用的自定义方法创建策略。每次它为在 laravel 7 中使用驼峰命名的自定义方法返回 403
例如。
class UserPostController extends Controller
{
public function __construct()
{
$this->authorizeResource(UserPost::class);
}
public function resourceMethodsWithoutModels()
{
return [
'getListing'
];
}
public function getListing(UserPostDataTable $dataTable)
{
dd(\Auth::user()->can('viewAny', UserPost::class));
// $this->authorize('viewAny', UserPost::class);
return $dataTable->ajax();
}
//Policy:
use App\User;
use App\UserPost;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Auth\Access\Response;
class UserPostPolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can view any models.
*
* @param \App\User $user
* @return mixed
*/
public function viewAny(User $user)
{
return Response::allow()
}
我已经添加$this->registerPolicies();
了服务提供者的引导方法。它适用于资源的所有 crud 操作,但不适用于自定义方法。
当我使用UserPost::class
它时返回 403。
如果我使用User::class
它可以完美运行。这似乎是一些命名问题,或者我错过了一些东西。
我也尝试过中间件,但不适用于驼峰命名法。
不知道如何为方法添加viewAny
策略。getListing
路线清单:
| GET|HEAD | UserPost | UserPost.index | App\Http\Controllers\UserPostController@index | web,auth:web,can:viewAny,user_post |
| | POST | UserPost | UserPost.store | App\Http\Controllers\UserPostController@store | web,auth:web,can:create,user_post |
| | GET|HEAD | UserPost/create | UserPost.create | App\Http\Controllers\UserPostController@create | web,auth:web,can:create,user_post |
| | POST | UserPost/getListing | UserPost.getListing | App\Http\Controllers\UserPostController@getListing | web,auth:web |
| | DELETE | UserPost/{UserPost} | UserPost.destroy | App\Http\Controllers\UserPostController@destroy | web,auth:web,can:delete,user_post |
| | PUT|PATCH | UserPost/{UserPost} | UserPost.update | App\Http\Controllers\UserPostController@update | web,auth:web,can:update,user_post |
| | GET|HEAD | UserPost/{UserPost} | UserPost.show | App\Http\Controllers\UserPostController@show | web,auth:web,can:view,user_post |
| | GET|HEAD | UserPost/{UserPost}/edit | UserPost.edit | App\Http\Controllers\UserPostController@edit | web,auth:web,can:update,user_post