How to make a loop variable?

$prices = Price::where('product_id','=',$id)->get(); // Получаем массив с ценами в магазинах foreach($prices as $row) { $store_data = Store::where('id','=',$row->store_id)->get(); foreach($store_data as $store) { echo ' <tr> <td><a href="/store/'.$store->id.'">'.$store->title.'</a></td> <td>'.$store->address.'</td> <td>'.$row->price.'</td> <td>'.$row->updated_at.'</td> </tr> '; } } 
  • What result is expected? What should end up in a variable? Table? - PCGeek 2:42 pm
  • As a result, the variable should be shielded, tobish <tr> - das
  • If I understood correctly, can a cycle be put into a function? Accordingly, it will return the required result - PCGeek
  • I am confused by the number of requests that you can do in a loop, maybe you should first get all id then use in query in select them 1 time `DB :: table ('store') -> whereIn ('id', array (1, 2 , 3)) -> get (); `and already cycle passes. ps just a sentence. if you specify what you need in the end get to try to help you. - Shadow33

1 answer 1

The Price - Store relationship must be configured.

 $tbody = ''; foreach(Price::with('store')->where('product_id', $id)->get() as $price) { // with() подгружает связанные сущности Store $tbody .= ' <tr> <td><a href="/store/' . $price->store->id . '">' .$price->store->title . '</a> </td> <td>' . $price->store->address . '</td> <td>' . $price->price . '</td> <td>' . $price->updated_at . '</td> </tr> '; } 

The result will be in $tbody .

If you do everything in a good way, then you need to transfer from the controller
$prices = Price::with('store')->where('product_id', $id)->get() and then in the template

 @foreach($prices as $price) <tr><a href="/store/{!! $price->store->id !!}">{!! $price->store->title !!}</a> </td> <td>{!! $price->store->address !!}</td> <td>{!! $price->price !!}</td> <td>{!! $price->updated_at !!}</td> </tr> @endforeach 

And of course the link is better to replace with route or action.