Eloquent multivalued value of a column of a relationship access table from a pivot table

I have two models:

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

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

      

and second:

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

      

My question is, how can I access the second column of the table using a pivot table:

products table:

id
title
image

      

order table:

id
status

      

pivot table (order_product):

id
product_id
order_id

      

I need to access the title column of products from orders. for example, if a user orders many products in the same order, I can get the entire product name and show the subject. I don't like using join, I like using Laravel functionality instead.

+3


source to share


1 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 an order.

0


source







All Articles