Gates and Policies (Laravel)
When authorizing access to different users, I found out that instead of doing this:
// in Controller.php
public function items(Request $request, MyModel $model)
{
$request_user_id = $request->user()->id;
$model_user_id = $model->user_id;
abort_if(
$model_user_id != $request_user_id,
403,
"Forbidden."
);
return ModelResource::collection($model->items);
}
I found out that you can create Policies by using artisan make:policy
, and it'll look like this:
// App/Policies/ModelPolicy.php
use Illuminate\Auth\Access\Response;
// ..snip
public function view(User $user, Model $model): Response
{
return $user->id === $model->user_id
? Response::allow()
: Response::deny('You are forbidden to access this resource.');
}
In the Controller.php
, it will be implemented like this:
// in Controller.php
public function show(Model $model)
{
// Uses ModelPolicy, the 'view' function
Gate::authorize('view', $model);
return new ModelResource($model);
}