Search code examples
laravellaravel-5.5

Laravel : Three table with relationship to get data


I have a 3 table in my app.products,category,attributes product hasMany category and category hasMany attributes relationship.

I want to get all products with Category details and catgoey attributes detail in json format.How can i do this?

Currently i am trying with this function in my controller:

public function index()
{
    $productDetails = Product::all();
    if(!empty($productDetails)) {
        foreach ($productDetails as $key => $value) {
            //print_r($value->id."</br>");
        }
    }
}

Output which i want :

       {
       "productInformation": {
            "id": 1,
            "name": "productone",
            "status": "Active",
            "CategoryDetails": [
                {
                    "id": 1,
                    "product_id": 1,
                    "categoryTitle": "categoryone",
                    "attribute" : [
                        {
                            "id": 1,
                            "product_id": 1,
                            "category_id": 1,
                            "title": "attrib-title-one",
                        },          
                        {
                            "id": 2,
                            "product_id": 1,
                            "category_id": 1,
                            "title": "attrib-title-two",
                        },
                    ]
                }
            ]
        }
    }

relationship :

On categories table

$table->foreign('product_id')->references('id')->on('products');

On attributes table :

 $table->foreign('product_id')->references('id')->on('products');
 $table->foreign('category_id')->references('id')->on('categories');

How can i do this ?


Solution

  • Your Product Model

    public function categories(){
    return $this->hasMany('App\Category','product_id');
    }
    

    Category Model

    public function attributes(){
    return $this->hasMany('App\Attribute','cat_id');
    }
    

    In your Controller

    public function index()
    {
        $productDetails = Product::with('catgories.attributes')->get();
        if(!empty($productDetails)) {
            $jsonData = json_encode($productDetails->toArray());
        }
    }