2 回答

TA貢獻1797條經(jīng)驗 獲得超6個贊
我的工作方法有兩個假設,在控制器中使用模型綁定(無論如何你都應該這樣做)。其次,位置與其所需的權限之間需要存在某種關系,類似于您建議的slug。
你的控制器功能看起來像這樣。添加 FormRequest 是執(zhí)行此邏輯的好方法。
class LocationController {
public function edit(EditLocationRequest $request, Location $location) { // implicit model binding
...
}
}
為了方便使用,我也會制定一個政策。
class LocationPolicy
{
public function edit(User $user, Location $location) {
return $user->permissions->pluck('name')
->contains($location->permission_slug); // assuming we have a binding
}
}
請記住在 中注冊策略AuthServiceProvider.php。
protected $policies = [
Location::class => LocationPolicy::class,
];
現(xiàn)在,在您的表單請求中使用授權方法中的策略。從這里,您處于請求上下文中,您可以訪問用戶,$this->user()并且可以訪問在其名稱上綁定模型的所有模型,例如$this->location。
class EditLocationRequest
{
public function authorize(): bool
{
return $this->user()->can('edit', $this->location);
}
}
現(xiàn)在您應該只能有一個路由定義。
Route::get('administration/location/{location}/edit', 'LocationController@edit')->name('location.edit');
編輯
如果您使用 AuthorizesRequests 特征,則無需表單請求即可執(zhí)行以下操作。這將拋出一個 AuthorizationException 失敗。
use AuthorizesRequests;
public function edit() {
$this->authorize('edit', $location);
}

TA貢獻1725條經(jīng)驗 獲得超8個贊
如果您有基于位置關系的要求,那么您將需要在數(shù)據(jù)中捕獲該關系。一個好的起點是添加特定于這些編輯權限的數(shù)據(jù)透視表??紤]一個表,location_permissions,帶有 auser_id和 a location_id。然后,一旦您擁有特定的用戶和位置,您就可以修改或添加權限中間件來檢查此表中的記錄。
編輯:回答有關中間件實現(xiàn)的問題,
通過這個新的數(shù)據(jù)透視表定義用戶模型與位置的關系可能會解決實現(xiàn)的關鍵問題。
我建議添加一個額外的方法,該方法locations按照以下方式消耗與模型的新關系
public function canEditLocation(Location $location): bool {
return $this->locations
->where('location_id', '=', $location->id)
->count() > 0;
}
實際的中間件是這樣的:
public function handle($request, Closure $next, $location)
{
if (! $request->user()->canEditLocation($location)) {
\\handle failed permission as appropriate here.
}
return $next($request);
}
我的中間件參數(shù)知識很生疏,但我相信這是正確的,如https://laravel.com/docs/master/middleware#middleware-parameters中定義的那樣
- 2 回答
- 0 關注
- 146 瀏覽
添加回答
舉報