Is it right way to show all user info with auth::guard laravel authentication

128 views Asked by At

I am newbie to laravel. I have question in my mind that... Is it right way to show all user information using auth::guard. I am using laravel breeze authentication ?

for ex. is it right -

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

like this ?

1

There are 1 answers

0
JedJonesUk On

This would work but might more commonly be written like this. If you are sure your user is logged in, then you skip any additional check of $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 might not be logged in, this you can add line specific checks 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 user might not be logged in and you want to ensure they always are, you can do this:

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