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

后端 未结 18 1620
小鲜肉
小鲜肉 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:30

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

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

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

    You can try :

    $id = \Auth::user()->id
    
    0 讨论(0)
  • 2020-12-04 12:32

    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.

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

    It's working with me :

    echo Auth::guard('guard_name')->user()->id;
    
    0 讨论(0)
  • 2020-12-04 12:33

    If anyone is looking for laravel 5 >

     Auth::id() 
    

    give id of the authorized user

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