【问题标题】:display the authenticated user in laravel在 laravel 中显示经过身份验证的用户
【发布时间】:2021-03-23 14:16:53
【问题描述】:

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

未定义变量:用户(查看: 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());

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

【问题讨论】:

标签: php mysql laravel laravel-6


【解决方案1】:

在你的例子中

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

你使用过“用户”

但试图以“用户”的身份访问变量

除非您只是在示例中打错字?

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2019-05-19
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多