0

Model function :

class Cart extends Model
{

   public static function cart()
   {
     $id = \Auth::user()->id;
     $count = Cart::where('user_id' , $id)->sum('quantity');
     return $count;
   }
}

But it shows Trying to get property 'id' of non-object at view page. Please help me how to solve this?

4
  • try auth()->user()->id Commented Jan 24, 2020 at 4:41
  • not work bro... Commented Jan 24, 2020 at 4:43
  • in __construct apply middleware auth public function __construct() { $this->middleware('auth'); } Commented Jan 24, 2020 at 4:58
  • Auth::id() ? try that Commented Jan 24, 2020 at 5:10

4 Answers 4

1

You can use Auth::User()->id; to get current user id.

Sign up to request clarification or add additional context in comments.

Comments

0

You have multiple options:

1) use Illuminate\Support\Facades\Auth;

   Auth::user()->id;

2) auth()->user()->id;

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

4) Auth::id();

Comments

0

Try this pass $userId rather then auth()
it's not good practice to call auth function inside model because auth is applyed on controller so from controller you can send auth user id

model will also work but good practice is keep auth inside your controller

class Cart extends Model
{

   public static function cart($userId)
   {
     $count = Cart::where('user_id' , $userId)->sum('quantity');
     return $count;
   }
}
``

Comments

0

Your error not depends to :

 $id = \Auth::user()->id;

Its ok. Your problem is ther you call record of Cart in this line:

 $count = Cart::where('user_id' , $id)->sum('quantity');

Use dd($id) and dd($count) to see that probably there is no Cart record with that feature in database. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.