Laravel get relation with another relation

SellerController.php

public function products()
    {
        $seller = Auth::user();
        $products = Seller::find($seller->id)->products; //return only products, I need to get category with this relation!!!
        return response()->json(['data' => $products], 200);
    }

This return seller’s products.

Seller.php

public function products() {
        return $this->hasMany('App\Models\Products', 'user');
    }

Products.php

function seller()
    {
        return $this->belongsTo('App\Models\Seller', 'user');
    }

    function Category()
    {
        return $this->hasOne('App\Models\Category','cat');
    }

Now I want to return category with products in seller controller, how can I do this?

>Solution :

Use with function

 $products = Seller::findOrFail($seller->id)->products()->with('Category')->get();

Leave a Reply