Laravel API: Return Only Current User's Profile

Today I had a challenge where I had an endpoint in my Laravel API that was fetching all the user's profile information. This is not good security.

For example, any user could fetch https://www.example.com/api/users/3 even if the current user_id was not 3. To only show the current user who is logged in and not the others, I added the auth() method to make sure the system only returns the current user's profile information.

for example:

CHANGED FROM:

    public function show(User $user)
    {
        return new UserResource($user);
    }

 

CHANGED TO:

    public function show(User $user)
    {
        $user = auth()->user(); // returns the current user profile only
        return new UserResource($user);
    }

Good resource: https://www.itsolutionstuff.com/post/how-to-get-logged-in-user-data-in-laravel-5example.html