Reputation: 892
I need to block users from visualizing other users profiles I have the following in my web.php:
Route::get('companyuser/{id}', [CompanyUserController::class, 'show'])
->middleware(['role:companyuser', 'can:show,user']);
I defined a policy
public function show(User $authenticatedUser, $user_model)
{
return $authenticatedUser === $user_model->id ? Response::allow() : Response::deny();
}
and added it to the AuthServiceProvider
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
User::class => CompanyUserPolicy::class,
];
But now the user is blocked from entering his own profile as well. What am I missing? Thanks for the help.
Upvotes: 1
Views: 225
Reputation: 7242
It looks like the policy show() method is comparing an object to an ID value. This will always return false because the $authenticatedUser
variable is a User
object, while $user_model->id
is likely an integer. Using strict type comparison ===
an int can never be equal to an object:
$authenticatedUser === $user_model->id
Instead the code should probably compare the id of both objects:
$authenticatedUser->id === $user_model->id
Laravel Models also have a built-in method public function is($model): bool
that can be used to verify two objects represent the same model (database record). Here is the same code using that method:
$authenticatedUser->is($user_model)
The final solution might look like this:
public function show(User $authenticatedUser, $user_model)
{
return $authenticatedUser->is($user_model) ? Response::allow() : Response::deny();
}
Upvotes: 2