realtebo
realtebo

Reputation: 25681

Laravel: what's the better method to retrieve current logged user and why?

I know two method:

The first is using a Request object param in the controller's function

public function index(Request $request)
{   
    $user = $request->user();
    return view('home');
}

The second is using directly the Auth facade.

public function index()
{   
    $user = Auth::user(); 
    return view('home');
}

Are there any diferences? Are one method better that the other one and, if, yes, why?

Upvotes: 1

Views: 44

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111859

This is only matter of preference, you can use:

public function index(Request $request)
{   
    $user = $request->user();
    return view('home');
}

or

public function index()
{   
    $user = Auth::user(); 
    return view('home');
}

or

public function index(Guard $auth)
{   
    $user = $auth->user(); 
    return view('home');
}

or

public function index()
{   
    $user = auth()->user(); 
    return view('home');
}

They will all work the same. There is no better or worse method for such simple piece of code.

In controller it doesn't make much difference but in case you write some services and you would like to test them (writing some unit tests for example), better solution would be in my opinion injecting Guard in constructor instead of running Auth facade or auth() helper.

Upvotes: 2

Agu Dondo
Agu Dondo

Reputation: 13579

The Auth facade provides a shortcut but the result is the same. You can always use \Auth::user() from your controller or views, on the other hand, if you want to use the $request variable, you need to pass it to your views.

Upvotes: 0

Related Questions