search

Home  >  Q&A  >  body text

Is it appropriate to display all user information using auth::guard laravel authentication?

<p>I am new to Laravel. I have a question in my mind... is it correct to use auth::guard to display all user information. Am I using Laravel Breeze authentication? </p> <p>For example. Is that so-</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>Like this? </p>
P粉256487077P粉256487077445 days ago479

reply all(1)I'll reply

  • P粉779565855

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

    This can work, but it's more common to write it like this. If you're sure your user is logged in, you can skip any extra checks for $user.

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

    If your user may not be logged in, you can add a row-specific check like this:

    <?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 ?? '';
    ?>

    If your users may not be logged in and you want to make sure they are always logged in, you can do the following:

    <?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;
    ?>

    reply
    0
  • Cancelreply