skip to Main Content

I have 3 tables – users, products and user_products. I try get user_products for user with products data. I can get user_products by $this->hasMany(ProductUser::class) but how can I get products atributes (title and other) from Product table in one query? Or I have to do query for every product? I’m new in Laravel, tnx.

2

Answers


  1. That sounds like a many-to-many relationship between users and products to me. I suggest set up a BelongsToMany relationship between theses two:

    use IlluminateDatabaseEloquentRelationsBelongsToMany;
    
    class User extends Model
    {
        public function products(): BelongsToMany
        {
            $this->belongsToMany(Product::class);
        }
    }
    

    And you can always retrieve data from the pivot table, in this scenario, that user_products table.

    Login or Signup to reply.
  2. In User Modal -> User.php

    public function products()
    {
        return $this->belongsToMany(Product::class, 'user_products');
    }
    

    In Product Modal -> Product.php

    public function users()
    {
        return $this->belongsToMany(User::class, 'user_products');
    }
    

    In your controller -> Eger load the product with user

    public function showUserProducts($userId)
    {
        $user = User::with('products')->find($userId);
        if (!$user) {
            return redirect()->back()->with('error', 'User not found');
        }
        return view('user.products', compact('user'));
    }
    

    In your blade file to show data -> user/ products.blade.php

    @foreach ($user->products as $product) 
        <h1>{{ $product->title }}</h1>
    @endforeach
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search