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

后端 未结 18 1619
小鲜肉
小鲜肉 2020-12-04 11:42

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

相关标签:
18条回答
  • 2020-12-04 12:34

    you must check is user loggined ?

    Auth::check() ? Auth::user()->id : null
    
    0 讨论(0)
  • 2020-12-04 12:37

    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();
    }
    
    0 讨论(0)
  • 2020-12-04 12:37

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

    0 讨论(0)
  • 2020-12-04 12:38

    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.

    0 讨论(0)
  • 2020-12-04 12:38

    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.

    0 讨论(0)
  • 2020-12-04 12:41

    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

    0 讨论(0)
提交回复
热议问题