I want to user orders data by specific month in a year.
Here is my order Table
id | user_id | price | quantity | total
Here is my order model
public function user() { return $this->belongsTo(User::class); }
Here is my user model
public function orders(){ return $this->hasMany(Order::class); }
In a controller, by doing this I get all user orders
$user= User::with('orders')->get(); dd($user->orders);
Now, How can I get specific month user orders detail? I want to show all user list with their order’s total amount by month.
Advertisement
Answer
Try this to get users with their orders’ total of September:
$users = User::withSum(['orders as september_total' => function ($query) { $query->whereMonth('created_at', '9'); // September }, 'total'])->get();
This will place a september_total
attribute on your resulting models.