Laravel 5 - How to get Auth user ID in controller, retrieve user data and display that data in view

12,388

You try to display users, but you only have one user (the one that is logged in). Also you can simplify it a bit by just using Auth facade and not doing an other database call to get the same user.

Controller:

public function profile()
{
    $user = Auth::user();
    return view('profile')->with(['user' => $user]);
}

View:

<div class="panel-body">
    Your user id is: {{ $user->id }}
    Your first name is: {{ $user->first_name }}
    Your last name is: {{ $user->last_name }}
</div>
Share:
12,388

Related videos on Youtube

user3489502
Author by

user3489502

Updated on September 15, 2022

Comments

  • user3489502
    user3489502 over 1 year

    New to the Laravel 5 framework (and OOP), I want to create a view where a user can view/edit his own user profile when he's logged in.

    What would be the syntax to get Auth user ID in controller, retrieve user data (from DB) and display that data in the profile view.

    I tried the following, but doesn't work.

    Controller:

    /**
     * Show the application user profile to the user.
     *
     * @return Response
     */
    public function profile()
    {
    
        $users = User::find(Auth::user()->id);
    
        return view('profile')->with(['users' => $users]);
    }
    

    Profile view:

    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Profil</div>
    
                <div class="panel-body">
                    Your user id is: {{ Auth::user()->id }}.
    
        <table>
    @foreach($users as $user)
        <tr>
            <td>{{ $user->first_name }}</td>
            <td>{{ $user->last_name }}</td>
    
        </tr>
    @endforeach
        </table>
    
    
    
                </div>
            </div>
        </div>
    </div>
    

    Thanks. Any help would be greatly appreciated

  • user3489502
    user3489502 almost 9 years
    I added use Auth; at the top of my controller, and it worked!! You rock! Thanks so much
  • Prabal Thakur
    Prabal Thakur over 6 years
    use Auth; is compulsory, so seekers do not confuse with one more error to correct themself.