
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.
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.
Random Code Snippet Queries: Laravel
- If condition in foreach loop in laravel
- Ignore Records where a field has NULL value in Laravel
- How to include header file in laravel
- How to send email in Laravel 11
- Method chaining in Laravel
- How to call model in blade laravel
- Docker important commands to run laravel application with docker
- How to customize or Change validation error messages
- How to Run CRON Job on LIVE SERVER on Cpanel in Laravel Project
- How to get the id of last record from collection object in laravel view
- How to get all posts which contains comments in laravel
- How to restore deleted records in laravel
- Get today records in Laravel
- Insert values in pivot table dynamically in laravel
- How to decrypt laravel password
- Insert dummy data in users table Laravel
- How to get list of all views file in laravel
- How to check query string exists or not in laravel blade
- Count all and get 10 records after where condition in laravel
- Datetime field in Laravel migration
- Laravel hasmany select not working
- Get comma separated email from input array
- How to upload image in laravel 8
- Laravel 9 route group with controller
- Calculate age from date of birth in Laravel