136

I'm getting the following error "trying to get a property of a non-object" when I submit a form to add a user, the error is apparently on the first line: Auth::user()->id of the following:

$id = Auth::user()->id;
$currentuser = User::find($id);
$usergroup = $currentuser->user_group;
$group = Sentry::getGroupProvider()->findById($usergroup);

$generatedPassword = $this->_generatePassword(8,8);
$user = Sentry::register(array('email' => $input['email'], 'password' => $generatedPassword, 'user_group' => $usergroup));

$user->addGroup($group);

Any ideas? I've searched for a while and everything I see says this should work fine. My user is logged in using the Sentry 2 authentication bundle.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Josh
  • 5,999
  • 8
  • 30
  • 43
  • Is there a column named id in your User table? If not, that's the issue. – OffTheFitz Jul 24 '13 at 13:49
  • Yep, id is there @OffTheFitz the table is called users – Josh Jul 24 '13 at 13:51
  • Correct me if I am wrong but you are trying to register a logged in user?? If you are using Sentry to register a user why are you calling `Auth::user();`? the Auth::user() returns the current logged in user, so you are trying to register a user which should be logged in, it doesn't make sense – Altrim Jul 24 '13 at 13:54
  • @Josh What about your model. Whats the protectedKey? – OffTheFitz Jul 24 '13 at 13:58
  • Hey @Altrim I'm actually trying to let an admin user register a new user (the form accepts the input of an email address) and giving that new user the same group as the admin's user_group. Later on the new users get an email to activate their account. It worked fine until I tried adding the group to the mix. – Josh Jul 24 '13 at 13:59
  • 2
    Well if you are using Sentry check the logged in user with `Sentry::getUser()->id`. The error you get is that the `Auth::user()` returns NULL and it tries to get id from NULL hence the error `trying to get a property from a non-object`. – Altrim Jul 24 '13 at 14:01
  • @Altrim ah, so silly of me, that works fine! Please chuck it in as the answer so I can vote it in as the correct one. Thank you to you too OffTheFitz. – Josh Jul 24 '13 at 14:06

24 Answers24

115

Now with laravel 4.2 it is easy to get user's id:

$userId = Auth::id();

that is all.

But to retrieve user's data other than id, you use:

$email = Auth::user()->email;

For more details, check security part of the documentation

Dr. MAF
  • 1,853
  • 1
  • 27
  • 45
72

If you are using Sentry check the logged in user with Sentry::getUser()->id. The error you get is that the Auth::user() returns NULL and it tries to get id from NULL hence the error trying to get a property from a non-object.

Altrim
  • 6,536
  • 4
  • 33
  • 36
53

Do a Auth::check() before to be sure that you are well logged in :

if (Auth::check())
{
    // The user is logged in...
}
Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43
jody_lognoul
  • 817
  • 7
  • 15
  • 3
    That's correct - first you must to Auth::check() if user is loggin. Then the Auth::getUser() will have an useful object :) – BlueMan Jan 21 '14 at 13:37
  • 1
    If you want to do this using blade templating: `@if(Auth::check()) {{Auth::user()->id}} @endif` (this is useful if you want to get the user's ID for javascript / ajax) – Cato Minor Jul 08 '15 at 16:25
  • what if laravel 6 ? – gumuruh Oct 23 '19 at 07:46
25

id is protected, just add a public method in your /models/User.php

public function getId()
{
  return $this->id;
}

so you can call it

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

remember allways to test if user is logged...

if (Auth::check())
{
     $id = Auth::user()->getId();
}
Karthick Kumar
  • 2,349
  • 1
  • 17
  • 30
maztch
  • 1,597
  • 19
  • 25
20

In Laravel 8.6, the following works for me in a controller:

$id = auth()->user()->id;
user761100
  • 2,171
  • 4
  • 23
  • 31
14

In Laravel 5.6 I use

use Auth;
$user_id = Auth::user()->id;

as the other suggestion

Auth::id()

seems to apply to older versions of Laravel 5.x and didn't work for me.

frankfurt-laravel
  • 3,731
  • 2
  • 20
  • 29
11

Never forget to include and try to use middleware auth:

use Illuminate\Http\Request;   

Then find the id using request method:

$id= $request->user()->id;
rashedcs
  • 3,588
  • 2
  • 39
  • 40
10

Check your route for the function in which you are using Auth::user(), For getting Auth::user() data the function should be inside web middleware Route::group(['middleware' => 'web'], function () {}); .

Ashwani Panwar
  • 3,819
  • 3
  • 46
  • 66
9

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();
Parveen Chauhan
  • 1,396
  • 12
  • 25
  • `Auth::user()->role` Solved my issue. `use Illuminate\Support\Facades\Auth;` is required to work with `Auth::user()`. Thank you for your answer – Mohamed Raza Jan 23 '21 at 13:33
7

If anyone is looking for laravel 5 >

 Auth::id() 

give id of the authorized user

Md Sifatul Islam
  • 846
  • 10
  • 28
6

use Illuminate\Support\Facades\Auth;

In class:

protected $user;

This code it`s works for me

In construct:

$this->user = User::find(Auth::user()->id);

In function:
$this->user->id;
$this->user->email;

etc..

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
l3okor
  • 61
  • 1
  • 3
4

you must check is user loggined ?

Auth::check() ? Auth::user()->id : null
Vahid Alvandi
  • 588
  • 9
  • 17
4

It's working with me :

echo Auth::guard('guard_name')->user()->id;
Abd Abughazaleh
  • 4,615
  • 3
  • 44
  • 53
3

Your question and code sample are a little vague, and I believe the other developers are focusing on the wrong thing. I am making an application in Laravel, have used online tutorials for creating a new user and authentication, and seemed to have noticed that when you create a new user in Laravel, no Auth object is created - which you use to get the (new) logged-in user's ID in the rest of the application. This is a problem, and I believe what you may be asking. I did this kind of cludgy hack in userController::store :

$user->save();

Session::flash('message','Successfully created user!');

//KLUDGE!! rest of site depends on user id in auth object - need to force/create it here
Auth::attempt(array('email' => Input::get('email'), 'password' => Input::get('password')), true);

Redirect::to('users/' . Auth::user()->id);

Shouldn't have to create and authenticate, but I didn't know what else to do.

julianstark999
  • 3,450
  • 1
  • 27
  • 41
Andrew Koper
  • 6,481
  • 6
  • 42
  • 50
3

The first check user logged in and then

if (Auth::check()){
    //get id of logged in user
    {{ Auth::getUser()->id}}

    //get the name of logged in user
    {{ Auth::getUser()->name }}
}
barbsan
  • 3,418
  • 11
  • 21
  • 28
Abid Shah
  • 325
  • 3
  • 5
3

For Laravel 6.X you can do the following:

$user = Auth::guard(<GUARD_NAME>)->user();
$user_id = $user->id;
$full_name = $user->full_name;
Ajjay Arora
  • 144
  • 2
  • 4
  • 10
3
 if(Auth::check() && Auth::user()->role->id == 2){ 
         $tags = Tag::latest()->get();
        return view('admin.tag.index',compact('tags'));
    }
  • Hi and welcome to stackoverflow, and thank you for answering. While this code might answer the question, can you consider adding some explanation for what the problem was you solved, and how you solved it? This will help future readers to understand your answer better and learn from it. – Plutian Jan 30 '20 at 09:06
3

Laravel 8 solution:

use Illuminate\Support\Facades\Auth;

// Retrieve the currently authenticated user...
$user = Auth::user();

// Retrieve the currently authenticated user's ID...
$id = Auth::id();

For more details, see the latest docs here

Omar Tariq
  • 7,536
  • 10
  • 38
  • 57
1

You can try :

$id = \Auth::user()->id
rashedcs
  • 3,588
  • 2
  • 39
  • 40
  • 1
    While this answer might technically be correct please provide a context as to why you think this would fix the problem and what it does E.G (When using namespaces anything in the global namespace needs to have a `\` before it to denote it's in the global namespace and not the current namespace) – Barkermn01 Jan 23 '20 at 17:02
1

You can try this for laravel 7 :

{{ Auth::user()->name  }}
mrhmt
  • 11
  • 2
0

As highlighted in the above feedback ensure that first and foremost is that you have defined the Auth Facade in your controller. Depending on the version of your laravel App the declaration of the Auth would look something like this :

5.8 and below

use Illuminate\Support\Facades\Auth;

version 6 and above

use Auth;

Also in your routes file ensure that the auth middleware encloses the route.

For a single endpoint try (Code sample for laravel 8)

Route::post('update-profile', [UserController::class, 'profileUpdate'])->middleware('auth:sanctum');

For multiple endpoints

Route::middleware(['auth:sanctum'])->group(function () {

  Route::post('update-profile', [UserController::class, 'profileUpdate']);

}
stanley mbote
  • 956
  • 1
  • 7
  • 17
0

2023's here. If the session is over and you are trying to reload old page it will still show that stuff . The only good solution I found out so far is to screw in a tail middleware('auth') to your route in web.php Say:

Route::get('/my_admin/{userid}', 'my\DearRoute@giveMeMyDarlingView')
    ->name('comeup_dear')->middleware('auth');

and now if in your browser lasts some out sessioned say https://myserver.com/my_admin/6 leavings and you are trying to refresh page it will kick you out to login page.

Edit: or if there are a lot of such routes embrace them into:

Route::middleware(['auth'])->group(function () {
  ...
   Route::get('/my_admin/{userid}', my\DearRoute@giveMeMyDarlingView')->name('comeup_dear')
  ...
});

still there in web.php

And you are done

CodeToLife
  • 3,672
  • 2
  • 41
  • 29
0

'user_id' => Auth::guard('travelGuard')->id()

  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/34388146) – treckstar May 18 '23 at 04:45
0

In laravel 10:

$id = auth()->id();

Reference:

vendor\laravel\framework\src\Illuminate\Contracts\Auth\Guard.php

/**
* Get the ID for the currently authenticated user.
*
* @return int|string|null
*/

public function id();
Ilyich
  • 4,966
  • 3
  • 39
  • 27