laravellaravel-7

How to find user by user name in laravel?


I am trying to find user by user name while building a laravel API. This is what I'm trying

api.php

Route::get('user-profile/user/{user}', 'UserProfileController@getUserProfile');

Controller

public function getUserProfile(User $user)
{
    $userId = User::where('userName', $user->userName)->first()->id; // I am expecting user id here like "1"
}

This causing 404 not found error.


Solution

  • by default route model binding search for id and in your case you want search by username so all you need is to remove dependency injection from your controller parameters like this

    public function getUserPortfolio($user) // fix it as $user only
    {
        $userId = User::where('userName', $user)->first()->id; // I am expecting user id here like "1"
    }