Joining four more table using Laravel Eloquent ORM

Viewed 48

I have a Category ID, Color ID, Size ID, Brand ID in a product table. How can I relate to all the tables using Eloquent ORM? I want to write a query in the product controller and bring all the data in the table. How can I do this without a query builder?

1 Answers

You need to made relationship in Product Model.

class Product extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category','category_id','id');
    }

    public function color()
    {
        return $this->belongsTo('App\Color','color_id','id');
    }
    public function size()
    {
        return $this->belongsTo('App\Size','size_id','id');
    }
    public function brand()
    {
        return $this->belongsTo('App\Brand','brand_id','id');
    }
}

Now in controller you can get as below.

$products = Product::with(['category','color','size','brand'])->get();
Related