首页 > 解决方案 > 在 laravel 中显示经过身份验证的用户

问题描述

您好,我正在尝试显示经过身份验证的用户,但出现此错误:

未定义变量:用户(查看:C:\wamp64\www\Blan\resources\views\users\index.blade.php)


这是我的代码:
用户控制器:
public function index()
{
    return view('users.index')->with('user', Auth::user());
    
}

风景 :

@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

但是,如果我在控制器中使用此代码返回所有用户:

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

它的工作正常。
那么我如何才能只返回当前经过身份验证的用户?

标签: phpmysqllaravellaravel-6

解决方案


您不需要通过控制器发送 auth 用户。Auth 是 laravel 中的全局外观。此外,您不需要 foreach,因为只有 1 个经过身份验证的用户。只需在要显示用户的刀片中键入 Auth::user()->name

是的,顺便说一句,你得到的错误是因为你正在为 $users 做 foreach 但将 $user 发送到刀片但我很确定即使你纠正了那个错字它也不会工作


推荐阅读