8

I am working on laravel 5.4, i have used the auth for user login at client side,now i want the logged in user details at the Controller,

view side by writing below code i got that:

{{ Auth::user()->name }} // this works on view page only.

Suggest me the library files with the code. I want to display some user data like name,age,dob,etc after logged in.

miken32
  • 42,008
  • 16
  • 111
  • 154
Anand Maurya
  • 170
  • 1
  • 1
  • 12

9 Answers9

27

The laravel Auth Facade is used to get the autheticated user data as

$user = Auth::user();
print_r($user);

This will work in your controller and view both, but you have to include it as

use Illuminate\Support\Facades\Auth;
RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
7

Just use the helper function you won't need to instantiate or import any class.

$user = auth()->user();

then dd($user); you'll have a full data on user.

you can then pull what you want.

$user->name

etc...

madeny
  • 463
  • 2
  • 13
3

This should work

use Illuminate\Support\Facades\Auth;

// Get the currently authenticated user...
$user = Auth::user();

But you have to use use

Vuk Stanković
  • 7,864
  • 10
  • 41
  • 65
2

Laravel has helpler for that. u can use auth() anywhere. for example:

auth()->user()->name

or check if not authentificated:

if(! auth()->user()){}
WebArtisan
  • 3,996
  • 10
  • 42
  • 62
2

You can access the user in any controller using

$user = Auth::user();

You should then be able to get details of the user by doing things like

$user_id = $user->id; //or Auth::user()->id;
$user_email = $user->email; // or Auth::user()->email;

See more details here https://laravel.com/docs/5.4/authentication#retrieving-the-authenticated-user

The Sammie
  • 1,218
  • 15
  • 25
2

You can use auth()->user->name

Goundo
  • 95
  • 10
2

Use the facade

use Illuminate\Support\Facades\Auth;

And

$user = Auth::user();

NOTE: You can call specific column in this library like $user = Auth::user()->name; or ->address etc.

Dharman
  • 30,962
  • 25
  • 85
  • 135
0

$user = Auth::user();

You could get the current user into the user variable.

iknow
  • 8,358
  • 12
  • 41
  • 68
0

For authentication purpose we can use middleware in controller given as below

public function __construct()
{
    $this->middleware('auth');
    
}

Then write in your function $user = Auth::user();