Eloquent many to many relationship access table column value from pivot table

400 views Asked by At

I have two models:

class Order extends Eloquent 
{
    public function User()
    {
        return $this->belongsTo('User');
    }

    public function Product()
    {
        return $this->belongsToMany('Product');
    }
}

and the second one is:

class Product extends Eloquent 
{
    public function Order()
    {
        return $this->belongsToMany('Order');
    }
}

My question is how can i access a value of second table column using pivot table:

product table:

id
title
image

order table:

id
status

pivot table(order_product):

id
product_id
order_id

I need to access title column of products from orders. for example if a user orders many products in one order I can fetch all product title and show theme. I don't like use join , instead I like to use Laravel functionality itself.

1

There are 1 answers

1
Amir H On BEST ANSWER

I found the answer:

$orders = Order::orderBy('created_at', 'DESC')->paginate($page_number);

foreach($orders as $item){
  foreach($item->product as $item){
     {{$item->title}}<br>
  }
}

I can access products from order.