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

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

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

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

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

    if (Auth::check())
    {
        // The user is logged in...
    }
    
    0 讨论(0)
  • 2020-12-04 12:27

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

    $id = auth()->user()->id;
    
    0 讨论(0)
  • 2020-12-04 12:28

    For Laravel 6.X you can do the following:

    $user = Auth::guard(<GUARD_NAME>)->user();
    $user_id = $user->id;
    $full_name = $user->full_name;
    
    0 讨论(0)
  • 2020-12-04 12:29
     if(Auth::check() && Auth::user()->role->id == 2){ 
             $tags = Tag::latest()->get();
            return view('admin.tag.index',compact('tags'));
        }
    
    0 讨论(0)
提交回复
热议问题