Skip to content
Advertisement

How to restrict a user to only see their own profile

I have a view (resources/view/front/auth/profile.blade.php) and my route in file web.php is:

JavaScript

My problem is that when a user logs in and gets redirected to their own profile page (http://exmaple.com/profile/2), he/she can change the URL to http://exmaple.com/profile/3 and see other users’ profile.

I want to use a middleware to check authenticated users id with URL parameter {user}. The $user->id will passed to the {user}, but I have no idea how.

Middleware UserProfile.php:

JavaScript

Advertisement

Answer

You can protect the route simply by removing the user id from the URL, but getting it through the authentication session instead.

So, your route signature should goes from:

JavaScript

To this:

JavaScript

So, in your controller, instead of getting the user id from the request:

JavaScript

You could get the logged-in User through the Auth facade:

JavaScript

or just the auth() helper:

JavaScript

This way, you are masking the URL to avoid a malicious user of doing things that he/she shouldn’t.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement