41

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"

Laerte
  • 7,013
  • 3
  • 32
  • 50
Mansour hassan
  • 625
  • 2
  • 6
  • 14

3 Answers3

63

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. 
Amitesh Bharti
  • 14,264
  • 6
  • 62
  • 62
28

You have to call user() method:

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

Or, if you want to get only the model:

$user = \Auth::user();
Laerte
  • 7,013
  • 3
  • 32
  • 50
12

Using Helper:

auth()->user()->id ;   // or get name - email - ...

Using Facade:

\Auth::user()->id ;   // or get name - email - ...

Using DI Container:

use Illuminate\Auth\AuthManager;
class MyClass
{
    private $authManager;
    public __construct(AuthManager $authManager)
    {
        $this->authManager = $authManager;
    }
}
automatix
  • 14,018
  • 26
  • 105
  • 230
Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144