1

I want to access the currently logged In user ID in the model. So in the model, I have written the codes;

namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Auth;

and in the method under the model, I used this code: Auth::user()->id However, I receives the error:

Trying to get property of non-object

  • https://stackoverflow.com/questions/37372357/laravel-how-to-get-current-user-in-appserviceprovider You can't get the auth user in service providers. – Chin Leung May 28 '18 at 13:31

6 Answers6

3

First you need to check if exists an user logged, then check the id

  if (Auth::check()) {
  //there is a user logged in, now to get the id
     Auth::user()->id
  }
2

Auth::user() is checking web guard only. You were probably trying this with an API. This will give you the user:

$user = \Auth::user() ?? \Auth::guard("api")->user();
schrink
  • 96
  • 3
1

To retrieve the id you must use:

Auth::id()

Other user properties are accessed like you tried

Auth::user()->otherProperties
Pol Lluis
  • 1,152
  • 7
  • 17
1
 use Illuminate\Support\Facades\Auth;

// Get the currently authenticated user...

$user = Auth::user();

// Get the currently authenticated user's ID...

$id = Auth::id();
foram kantaria
  • 748
  • 6
  • 11
0

You have to be logged in to get the current logged user.

Try checking for logged in user before using it

if (Auth::user()) {   // Check is user logged in
           // do stuff

        } 
Ionel Lupu
  • 2,695
  • 6
  • 29
  • 53
0

You can get easily logged in user id in model. Try bellow code. It's working perfect.

app('Illuminate\Contracts\Auth\Guard')->user()->id;
Dwarkesh Soni
  • 289
  • 3
  • 16