skip to Main Content

I made a link using

Route::get('/admin/edit/user/{user_id}', [UserController::class, 'editUser'])->name('edit.user');

That is why when a user click on edit he see https://0608sns.org/admin/edit/user/1789
and he can edit his profile but if that user put another id like 1790 he can use that user profile.
So, How can i prevent it?

2

Answers


  1. You have to use Policies to allow an entity to do something or not.

    In your example, you should create a Policy called UserPolicy with php artisan make:policy UserPolicy, and the contents of it should be:

    <?php
     
    namespace AppPolicies;
     
    use AppModelsUser;
     
    class UserPolicy
    {
        public function update(User $user, User $userToEdit): bool
        {
            return $user->id === $userToEdit->id;
        }
    }
    

    Then, in your controller, you should have something like this:

    public function update(Request $request, int $user_id): RedirectResponse
    {
        $userToEdit = User::findOrFail($user_id);
    
        $this->authorize('update', $userToEdit);
    
        // Do whatever you need to
    
        return redirect('/');
    }
    

    I may be missing something, this is from the top of my head, so try it out and let me know if it worked or not.

    Login or Signup to reply.
  2. Actually you just need a simple Gate [Policies also great]
    But for simple authorizations like this, we prefer Gates.
    Go over here https://laravel.com/docs/10.x/authorization#writing-gates

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search