OndOne
OndOne

Reputation: 27

Output by putting together two more databases in Laravel 5.5

I am using Laravel 5.5. I already coded full CMS, and booking system. I have got three tables:

So after many orders done, the Orders table will just contain userid (which corresponds with users primary key in Users table) and offerid (which corresponds with offer primary key in Offers table).

I want to output this together in a View, by a list (all orders), each row should contain user data by finding primary key of an user in User table by an userid in Orders table, and in a same row offer data by finding offer by its primary key which corresponds with offerid in Orders table.

I was thinking like building really big multidimensional array in controller function by using eloquent and then passing it to a desired view, but I got stuck there.

Is there any option to do this this way or is my thinking like above very wrong for this case?

This is how mentioned controller function look:

public function index(){
$allorders=Order::all();
$bigarray=array();

foreach($allorders as $oneorder){
$bigarray[]=array(
'idorder'=>$oneorder->id,
           'user'=>User::find($oneorder->userid),
           'offer'=>Order::find($oneorder->offerid)
       );
 }

    return view('desiredview...')->with('bigarray',$bigarray);

Please don't consider the eloquent find static as a mistake; I admit I stuck there, the thing is I am really out of ideas how to output list of orders in a view by a way I described above. Otherwise if I don't find a solution I was thinking of putting all data-users and offer data in one row in an Orders table, but it is a easy way to do, but a little chaotic after some time, when doing a lot of data.

Upvotes: 0

Views: 46

Answers (1)

robbyrr
robbyrr

Reputation: 392

Use Relationships:

In your Order model:

public function user()
{
    return $this->belongsTo(User::class);
}

public function offer()
{
    return $this->belongsTo(Offer::class);
}

And then in your Controller:

public function index()
{
    $allOrders=Order::all();

    return view('desired.view', compact('allOrders'));
}

And in your view you can loop over the orders:

<table>
  <thead>
    <tr>
      <th>Order Id</th>
      <th>User Name</th>
      <th>Offer Name</th>
    </tr>
  </thead>
  <tbody>
@foreach($allOrders as $order)
    <tr>
        <td>{{$order->id}}</td>
        <td>{{$order->user->name}}</td>  //Here you have the corresponding User model
        <td>{{$order->offer->name}}</td> //Name is just an example, use whatever you want from your model.
    </tr>
@endforeach
  </tbody>
</table>

In the foreach loop you then have the User and Offer model, I suggest you read the laravel docs about relationships. It's easy and well explained.

Upvotes: 1

Related Questions