繁体   English   中英

在 laravel 中显示经过身份验证的用户

[英]display the authenticated user in laravel

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

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


这是我的代码:
用户控制器:
return view('users.index')->with('users', User::all());

风景:

 @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

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

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

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

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

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

在你的例子中

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

您使用了“用户”

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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