Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dharmendrarao's avatar

How i can get data from multiple models

Hi,

i have 4 models

Products field id, name

Categories field id, name

CategoryProducts field id, product_id, category_id

CleanURL field id, product_id, category_id, clean_url

I want to fetch all products belong to specific category id and also want to fetch url of those product that belongs to specified category

i have created this method into Category model


public function Products()
{
    return $this->belongsToMany('App\Product', 'category_products', 'category_id', 'product_id');
}
it gives me all product info related to requested category by this call in category controller

$allproductData = Category::find($alldata[0]->category_id)->Products;
but i don't know that how i get url of product that i get from this request?

please let me know how i can achieve this

Thanks

0 likes
6 replies
xmarks's avatar

Create another Method url:

// Inside Product.php Model
public function url()
{
    return $this->belongsTo('App\CleanURL', 'clean_url', 'product_id', 'id');
}

And you can call it:

$categories = Category::with('products.url')->get();

Then you can do the following:

@foreach($category->products as $product)
    {{ $product->url }}
@endforeach
dharmendrarao's avatar

@xmarks thanks for reply.

i create function and call according you suggested but it give

This page isn’t working 127.0.0.1 is currently unable to handle this request. HTTP ERROR 500

in


$categories = Category::with('products.url')->get();
products, is method from Category model and url is method from Product model?
dharmendrarao's avatar

Hi,

i have added this into Product model


public function ProductUrl()
    {
        return $this->belongsTo('App\CleanURL', 'id', 'product_id');
    }

and call this with Products method of Category model like this


public function Products()
    {
        return $this->belongsToMany('App\Product', 'category_products', 'category_id', 'product_id')->with('ProductImages')->with('ProductUrl');
    }

and now i get all result which i am looking for

Please or to participate in this conversation.