Laravel 5 want to access auth user id in model

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

Upvotes: 1

Views: 9942

Answers (6)

schrink
schrink

Reputation: 96

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

Upvotes: 2

Dwarkesh Soni
Dwarkesh Soni

Reputation: 297

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

app('Illuminate\Contracts\Auth\Guard')->user()->id;

Upvotes: 0

foram kantaria
foram kantaria

Reputation: 786

 use Illuminate\Support\Facades\Auth;

// Get the currently authenticated user...

$user = Auth::user();

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

$id = Auth::id();

Upvotes: 1

Alejandro L.Rocha
Alejandro L.Rocha

Reputation: 1145

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
  }

Upvotes: 3

Pol Lluis
Pol Lluis

Reputation: 1162

To retrieve the id you must use:

Auth::id()

Other user properties are accessed like you tried

Auth::user()->otherProperties

Upvotes: 1

Ionel Lupu
Ionel Lupu

Reputation: 2801

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

        } 

Upvotes: 0

Related Questions