简体   繁体   中英

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM