Laravel 拉维尔5号线路保护
假设我们有一个具有多对多关系的用户和会话模型Laravel 拉维尔5号线路保护,laravel,routing,Laravel,Routing,假设我们有一个具有多对多关系的用户和会话模型 class User extends Model ... { public function conversations() { return $this->belongsToMany('App\Conversation'); } } class Conversation extends Model { public function users() { retu
class User extends Model ... {
public function conversations()
{
return $this->belongsToMany('App\Conversation');
}
}
class Conversation extends Model {
public function users()
{
return $this->belongsToMany('App\User');
}
}
除了laravel提供的身份验证(登录)之外:我如何为其相关用户保护特定的会话路由
实现这一目标最容易维护的方法是什么?中间件?警卫路由模型绑定。。。现在我有点迷路了…问得好。在这种情况下,最好使用Laravel的功能。区别如下:
class ConversationPolicy {
public function view(User $user, Conversation $conv) {
return in_array($user->id, $conv->users->pluck('id'));
}
}
您可以在控制器中检查策略,如下所示:
if($request->user()->can('view', $conversation))
{
return view('conversation', ['conversation' => $conversation]);
}
return back()->withError('You are not authorized to view this conversation');
请注意,您必须先在AuthServiceProvider中绑定此策略,然后才能使用它。好问题。在这种情况下,最好使用Laravel的功能。区别如下:
class ConversationPolicy {
public function view(User $user, Conversation $conv) {
return in_array($user->id, $conv->users->pluck('id'));
}
}
您可以在控制器中检查策略,如下所示:
if($request->user()->can('view', $conversation))
{
return view('conversation', ['conversation' => $conversation]);
}
return back()->withError('You are not authorized to view this conversation');
请注意,您必须先在AuthServiceProvider中绑定此策略,然后才能使用它。感谢您提供的详细解释。工作起来很有魅力。它应该是
$conv->users->pull('id')
,没有括号,对吗?是的。抢手货更新了原始版本以进行修复。感谢您的解释。工作起来很有魅力。它应该是$conv->users->pull('id')
,没有括号,对吗?是的。抢手货更新原始版本以修复。