Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get current user id in laravel 5.4 [duplicate]

I used this code in Laravel 5.4 to get the current logged in user id

    $id = User::find(Auth::id());     dd($id); 

but I receive "Null"

like image 300
Mansour hassan Avatar asked Aug 05 '17 13:08

Mansour hassan


2 Answers

You may access the authenticated user via the Auth facade:

use Illuminate\Support\Facades\Auth;  // Get the currently authenticated user...  $user = Auth::user();  // Get the currently authenticated user's ID...  $id = Auth::id(); 

You may access the authenticated user via an Illuminate\Http\Request

use Illuminate\Http\Request; public function update(Request $request) {      $request->user(); //returns an instance of the authenticated user...      $request->user()->id; // returns authenticated user id.  } 

via the Auth helper function:

auth()->user();  //returns an instance of the authenticated user... auth()->user()->id ; // returns authenticated user id.  
like image 92
Amitesh Bharti Avatar answered Sep 22 '22 07:09

Amitesh Bharti


You have to call user() method:

$id = \Auth::user()->id; 

Or, if you want to get only the model:

$user = \Auth::user(); 
like image 29
Laerte Avatar answered Sep 24 '22 07:09

Laerte