[英]How do i pass number to middleware “can” in Laravel Authorization
based on documentation https://laravel.com/docs/5.5/authorization#via-middleware基于文档https://laravel.com/docs/5.5/authorization#via-middleware
use App\Post;
Route::put('/post/{post}', function (Post $post) {
// The current user may update the post...
})->middleware('can:update,post');
the 'post' in 'can:update,post' is variable passed from '{post}'. 'can:update,post' 中的 'post' 是从 '{post}' 传递的变量。
im trying to use middleware('can:update,1') .我正在尝试使用中间件('can:update,1') 。 its not working.它不工作。 maybe its search for '$1' variable, how to pass number '1' to 'can' middleware?也许它搜索 '$1' 变量,如何将数字 '1' 传递给 'can' 中间件?
update this is the gate:更新这是门:
Gate::define('update', function ($user, $role){
$id = $user->id;
$roles = $user::find($id)->roles()->get();
$roleid = $roles[0]->pivot->role_id;
//above code just for get role id, and $role_id is 1
return $roleid === $role;
});
Probably you don't have Policy created for Post.可能您没有为 Post 创建策略。
You can create by command:您可以通过命令创建:
php artisan make:policy PostPolicy --model=Post
and then implement method update in that policy.然后在该策略中实现方法更新。
I to had this same problem so I did some digging into the 'can' middleware (Which maps to Illuminate\\Auth\\Middleware\\Authorize
)我遇到了同样的问题,所以我对“can”中间件进行了一些挖掘(它映射到Illuminate\\Auth\\Middleware\\Authorize
)
Once in the class we see the following code进入类后,我们会看到以下代码
/**
* Get the model to authorize.
*
* @param \Illuminate\Http\Request $request
* @param string $model
* @return \Illuminate\Database\Eloquent\Model|string
*/
protected function getModel($request, $model)
{
if ($this->isClassName($model)) {
return trim($model);
} else {
return $request->route($model, null) ?:
((preg_match("/^['\"](.*)['\"]$/", trim($model), $matches)) ? $matches[1] : null);
}
}
What this means is...这意味着……
"/^['\\"](.*)['\\"]$/"
2 尝试通过正则表达式"/^['\\"](.*)['\\"]$/"
从字符串中获取模型So now lets say we have the middleware call of $this->middleware(sprintf("can:create,%s,%s", User::class, Role::SUPPORT));
所以现在假设我们有$this->middleware(sprintf("can:create,%s,%s", User::class, Role::SUPPORT));
的中间件调用$this->middleware(sprintf("can:create,%s,%s", User::class, Role::SUPPORT));
This will not work because the Role::SUPPORT
does not match the regex这将不起作用,因为Role::SUPPORT
与正则表达式不匹配
To match it we simply need to place the Role::SUPPORT
into quotes.为了匹配它,我们只需要将Role::SUPPORT
放入引号中。
TAKE NOTE OF THE "'" around the second %s $this->middleware(sprintf("can:create,%s,'%s'", User::class, Role::SUPPORT));
注意第二个 %s 周围的 "'" $this->middleware(sprintf("can:create,%s,'%s'", User::class, Role::SUPPORT));
To answer your question specifically, quote your '1' value要具体回答您的问题,请引用您的“1”值
middleware("can:update,'1'").
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.