Count when a user order a product

Viewed 129

I want make count when a user login and make order about some product This is my table

  • User : Id(1 to many->order), name, email, address, phone

  • order : Id, id_user, id_product, date, price, total_order, total_price

I have written

$count = order::where('id_user','Auth->user()')->count();

Code above does not work, if I write like this

$count = order::all()->count();

It work but count all the data even i login with different user

3 Answers

You have to try this its working properly

$count = order::where('id_user',auth()->user()->id)->count();

OR

$count = order::where('id_user',auth()->id())->count();

'Auth->user()' firstly you tried a string not the id of logged user, you have to remove the quotation marks and add the use Auth; to import this class and then use it.

use Auth;

$count = order::where('id_user', Auth::user()->id)->count();

Make a relation from the user model

public function orders(){
    return $this->hasMany(Order::class, 'parent_id', 'id');
}

Then you can call wherever you want like this

auth()->user()->orders->count()
Related