Search code examples
laraveldelete-row

How to make sure a user can only delete his own records using Laravel


How to make sure a user can only delete his own records.

Here how i am deleting a post with the following url.

http://example.com/dashboard/sessions/delete/{id}

Now user can also pass any post id here and then record will be deleted for that id regardless if the post does not belong to user. How can i overcome this issue using Laravel


Solution

  • The best way is to use policies for this purpose

    Policies are classes that organize authorization logic around a particular model or resource. For example, if your application is a blog, you may have a Post model and a corresponding PostPolicy to authorize user actions such as creating or updating posts.

    If for some reason you don't want to use policies, you can check user manually:

    if (auth()->check && auth()->user()->id === $post->user_id) {
        // Delete post.
    }