Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

482
Views
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?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!