【发布时间】:2023-03-18 07:35:01
【问题描述】:
我使用中间件来限制非管理员访问管理页面,并且我可以通过使用策略来限制具有其他用户的“患者”列表的页面,但如果我使用策略。我必须在每个函数中重复代码 can() 方法。如果我使用中间件检查 url 中的 user_id 是否 == Auth::user()->id。我不需要重复这个,但是我如何从我的中间件的 url 中获取 user_id?
路线
Route::get('/patients/{patient}', 'PatientController@edit')
我现在拥有的
PatientPolicy
public function view(User $user, Patient $patient)
{
// does this patient belong to user
return $user->id == $patient->user_id;
}
病人控制器
public function edit(Patient $patient)
{
// authenticate logged in user
$user = auth()->user();
// can the loged in user do this?(policy)
if($user->can('update', $patient)){
return view('patient.edit-patient', compact('patient', 'user'));
}
return view('403');
}
我应该在中间件中拥有什么
用户中间件
/**
* @param $request
* @param Closure $next
* @return mixed
*/
public static function handle($request, Closure $next)
{
if (Auth::check() && Auth::user()->id == User::patients()->user_id) {
return $next($request);
} else {
return redirect()->route('login');
}
}
有人知道如何检查路由 user_id 中的 {患者} 是否 == 登录的 user()->id 吗?
【问题讨论】:
标签: laravel middleware restrict