Ad

Laravel 5.7 Get Data From Pivot Table

- 1 answer

I'm trying to get data from my pivot table.

clients table:

---|------
id | name
---|------
1  | John
---|------
2  | Steve

orders table:

---|------
id | description
---|------
1  | Mac
---|------
2  | Keyboard
---|------
3  | Printer

client_order (pivot)table:

    id | client_id | order_id
    ---|-----------|------
    1  | 1           1
    ---|-----------|------
    2  | 1         | 2
    ---|-----------|------
    3  | 2         | 3

Client.php

 public function orders()
{
    return $this->belongsToMany('App\Order','client_order');
}

Order.php

public function clients()
{
    return $this->belongsToMany('App\Client','client_order');
}

Now, how can I retrieve data from pivot table? For example:

John | Mac, Keyboard (2 orders)
Steve| Printer (1 orders)

Thank you.

Ad

Answer

For client:

$client = Client::find(1); //or anyway you create the client
$client->orders; //it gives you a collection that you can get data 
in a foreach loop
//for example
foreach($client->orders as $order){
    echo $order->description;
}

For order:

$order = Order::find(1); //or anyway you create order
$order->clients; //it gives you a collection too
//for example
foreach($order->clients as $client){
    echo $client->name;
}

This is for your new comment. First you select your users and then in a loop you can get the orders:

$clients = Client::all();
foreach($clients as $client){
    echo $client->name." | ";
    foreach($client->orders as $order){
        echo $order->description;
    }
    echo "(".count($client->orders)." orders)";
}
Ad
source: stackoverflow.com
Ad