3

I am having issues grabbing the currently authenticated user in Laravel 5.3. More specifically, I am making a HTTP request to my api.php file, which has the route defined as api/test/create.

The controller code:

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Test; class TestController extends Controller { public function store(Request $request) { $this->validate($request, [ 'test_name' => 'required', 'youtube_id' => 'required', 'is_live_test' => 'required', ]); //Laravel 5.3 allows to get the user via request $user = $request->user; if($user) { return 'We are logged in'; } else { return 'We are not logged in'; } return ''; } } 

Every time it returns 'We are not logged in'. To test this out, I referenced {{ Auth::check() }} in my blade file, and that returns as '1'. I am not quite sure why the Controller does not recognize the user is logged in; any ideas?

I have tried different variations of referencing the authentication, including importing the Facade and doing Auth::check(), Auth::user(), but it brings the same result regardless.

13
  • 1
    its $request->user() and you need to make sure the route uses the auth middleware Commented Jan 10, 2017 at 16:08
  • 1
    the api middleware should have auth:api Commented Jan 10, 2017 at 16:16
  • 1
    and when using the api routes, you need to setup passport: laravel.com/docs/5.3/passport Commented Jan 10, 2017 at 16:18
  • 1
    More specifically, for your users to consume the api: laravel.com/docs/5.3/… Commented Jan 10, 2017 at 16:19
  • 1
    You will not be able to access the api route by going to the url directly Commented Jan 10, 2017 at 17:03

3 Answers 3

3

Get user object with:

$user = $request->user(); 

Or:

$user = auth()->user(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the heads up -- still getting the 'not logged in', though.
Please show routes file contents. Also what routes file do you use?
3

You can use:

Auth::user(); 

also

auth()->user(); 

also

$request->user(); 

Comments

1

You can use Auth::check() method directly in the Controller.

if (Auth::check()){ // User is logged in // Do something with the Authenticated User. }else { // User is not logged in } 

to get User Data do something like this

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

etc.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.