搜索

首页  >  问答  >  正文

使用 auth::guard laravel 身份验证显示所有用户信息是否合适?

<p>我是 Laravel 的新手。我心中有一个问题...使用 auth::guard 显示所有用户信息是否正确。我正在使用 Laravel Breeze 身份验证?</p> <p>例如。是这样吗-</p> <pre class="brush:php;toolbar:false;">name: Auth::guard('web')->user()->name mobile: Auth::guard('web')->user()->mobile address: Auth::guard('web')->user()->address city: Auth::guard('web')->user()->city gender: Auth::guard('web')->user()->gender</pre> <p>像这样吗?</p>
P粉256487077P粉256487077477 天前500

全部回复(1)我来回复

  • P粉779565855

    P粉7795658552023-09-05 11:13:17

    这可以工作,但更常见的是这样写。如果您确定您的用户已登录,则可以跳过 $user 的任何额外检查。

    <?php
    $user = Auth::guard('web')->user();
    name: $user->name;
    mobile: $user->mobile;
    address: $user->address;
    city: $user->city;
    gender: $user->gender;
    ?>

    如果您的用户可能未登录,您可以添加特定于行的检查,如下所示:

    <?php
    $user = Auth::guard('web')->user();
    
    name: $user->name ?? null;
    mobile: $user->mobile ?? null;
    address: $user->address ?? null;
    city: $user->city ?? null;
    gender: $user->gender ?? null;
    
    //OR, when outputting in html
    
    name: $user->name ?? '';
    mobile: $user->mobile ?? ''
    address: $user->address ?? '';
    city: $user->city ?? '';
    gender: $user->gender ?? '';
    ?>

    如果您的用户可能未登录,而您想确保他们始终登录,您可以执行以下操作:

    <?php
    $user = Auth::guard('web')->user();
    if($user === null){
       throw new AuthenticationException('User Not logged in');
    }
    name: $user->name;
    mobile: $user->mobile;
    address: $user->address;
    city: $user->city;
    gender: $user->gender;
    
    //OR
    
    $user = Auth::guard('web')->user();
    if($user === null){
       abort(401)
    }
    name: $user->name;
    mobile: $user->mobile;
    address: $user->address;
    city: $user->city;
    gender: $user->gender;
    ?>

    回复
    0
  • 取消回复