Get the products list ordered by a user

Created at 08-Dec-2024 , By samar

$user  = Auth::user();
$products = Product::whereHas('orders', function($query) use ($user) {
    $query->where('user_id', $user->id);
})->get();

Method to get the orders list ordered by a user

$user = Auth::user();
$orders = $user->orders()->with('products')->get()->pluck('products')->flatten();

Add orders method in Product model

class Product extends Model
{
    /** @use HasFactory<\Database\Factories\ProductFactory> */
    use HasFactory;

    protected $fillable = ['name', 'description'];
    

    public function orders() {
        return $this->belongsToMany(Order::class, OrderProduct::class);
    }

}

You must have a pivot table named OrderProduct with column product_id and order_id

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.