0

I have two model, Category and Brand with many to many relation

in Category model

public function brands()
    {
        return $this->belongsToMany(Brand::class, 'brand_category', 'category_id', 'brand_id');
    }

and in brand model

    public function categories()
    {
        return $this->belongsToMany(Category::class, 'brand_category','brand_id','category_id' );
    }

how can i get brands with specific category id like json below

{
    "data": [
        {
            "brand_id": 1,
            "name": "Sony",
            "description": null,
            "logo": null,
            "is_active": true,
            "created_at": "2020-04-08 15:19:44",
            "updated_at": "2020-04-08 15:19:44",
            "deleted_at": null,
            "pivot": {
                "category_id": 1,
                "brand_id": 1
            }
        },
        {
            "brand_id": 2,
            "name": "Lg",
            "description": null,
            "logo": null,
            "is_active": true,
            "created_at": "2020-04-08 15:19:44",
            "updated_at": "2020-04-08 15:19:44",
            "deleted_at": null,
            "pivot": {
                "category_id": 1,
                "brand_id": 2
            }
        }
    ],
    "success": true,
    "error": {
        "code": 200,
        "data": []
    },
    "message": ""
}

i want to find a way without changing relations in models by wherePivot...

1 Answer 1

1

this should do.

return Category::find($categoryId)->brands;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.