[php] Laravel: Auth::user()->id trying to get a property of a non-object

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.

This question is related to php authentication laravel laravel-4

The answer is


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();
}

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;

For Laravel 6.X you can do the following:

$user = Auth::guard(<GUARD_NAME>)->user();
$user_id = $user->id;
$full_name = $user->full_name;

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 () {}); .


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


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

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

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.


You can try :

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

It's working with me :

echo Auth::guard('guard_name')->user()->id;

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

if (Auth::check())
{
    // The user is logged in...
}

If anyone is looking for laravel 5 >

 Auth::id() 

give id of the authorized user


 if(Auth::check() && Auth::user()->role->id == 2){ 
         $tags = Tag::latest()->get();
        return view('admin.tag.index',compact('tags'));
    }

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 }}
}

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.


you must check is user loggined ?

Auth::check() ? Auth::user()->id : null

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..


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();

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to authentication

Set cookies for cross origin requests How Spring Security Filter Chain works What are the main differences between JWT and OAuth authentication? http post - how to send Authorization header? ASP.NET Core Web API Authentication Token based authentication in Web API without any user interface Custom Authentication in ASP.Net-Core Basic Authentication Using JavaScript Adding ASP.NET MVC5 Identity Authentication to an existing project LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server