Support the ongoing development of Laravel.io →
Database Eloquent

Hi guys,

I'm fairly new to Laravel, I'm designing an application which will have an API which returns database results in JSON format. For this example I'm using 4 tables :

  • Items of type 1
  • items of type 2
  • Comments
  • Users

So, every item has a user and a thread of comments. What I'm trying to achieve is something like the following:

"post" :
{
  item id
  item pic
  user:
  {
    user id
    user pic
  }
  comments
  [
   {
    comment_id,
    comment_text,
   },
   {
    comment_id,
    comment_text,
   }
  ]
}

so to retrieve the type 1 and 2 items, i'm doing this :

	$items1 = DB::table('items1')->select('id','user_id','name','pic','created_at');
	$items2 = DB::table('items2')->select('id','user_id','name','pic','created_at');

then I join them :

    $combined = $items1->union($items2)->orderBy('created_at','desc')->get();

My question is, what is the most efficient way to get the user info and comments info for each item? It could be a long list so I want to be sure that I use the framework resources properly instead of put my own SQL code here and there.

Thank you in advance for your help.

Last updated 3 years ago.
0

Try use Eloquent ORM you can read the documentation here http://laravel.com/docs/eloquent

Last updated 3 years ago.
0

@darwingluague9001 Thank you for your answer. I solved it adding this:

    foreach($combined as $element)
    {
        $uid = $element->user_id;
        $element->user = DB::table('users')->select('id','pic')->where('id',$uid)->get();        
    }
Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.