Warm tip: This article is reproduced from serverfault.com, please click

display the authenticated user in laravel

发布于 2020-12-12 10:01:10

Hello i'm trying to display the authenticated user but i'm getting this error :

Undefined variable: users (View: C:\wamp64\www\Blan\resources\views\users\index.blade.php)


this is my code :
usercontroller :
public function index()
{
    return view('users.index')->with('user', Auth::user());
    
}

the view :

@extends('layouts.app')

@section('content')

<div class="card">
    <div class="card-header">
        Update Your Profile
    </div>

    <div class="card-body">
        <table class="table table-hover">
            <thead>
                <th>Image</th>
                <th>Name</th>
                <th>Update</th>
            </thead>
            <tbody>
                @if( $users -> count() > 0 )

                    @foreach ($users as $user)
                        <tr>
                            <td>
                                @if(isset($user->profile->avatar))

                            <img src="{{ asset($user->profile->avatar)}}" width="60px" height="60px" style="border-radius: 50%" alt="">
                                @else 
                            No image
                            @endif
                            </td>

                            <td>
                                {{$user->name}}
                            </td>

                            <td>
                                <a href="#" class="btn btn-success">Update</a>
                            </td>
                        </tr>
                    @endforeach
                @else 
                <tr>
                    <th colspan="5" class="text-center">No Users </th>
                </tr>
                @endif
            </tbody>
        </table>
    </div>

</div>    
@stop

But if i return all the users using this code in the controller :

return view('users.index')->with('users', User::all());

its work fine.
so how i can return only the current authenticated user ?

Questioner
MARYAM
Viewed
0
Rastko Todorovic 2020-12-12 18:33:13

You don't need to send the auth user via your controller.Auth is the global facade in laravel.Also you don't need foreach because there is only 1 authenticated user. Just type Auth::user()->name in the blade where you want to display the user

Yea and btw the error ur getting is because you are doing foreach for $users but sending $user to blade but im pretty sure it wont work even if you correct that typo