Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Query result from two tables into one collection

Hello,

I try to have the result of two queries in one collection.

$creations = Drawing::where('published', 1)->orderBy('creation_date', 'desc')->limit(4)->get();
return view('accueil', compact('creations'));
$creations = Animations::where('published', 1)->orderBy('creation_date', 'desc')->limit(4)->get();
return view('accueil', compact('creations'));

Of course I could have a unique table, but there are very differents fields, so I have two different tables. How can I have both Drawing and Animations in one query ?

Thank you for your help.

0 likes
3 replies
ismaile's avatar
ismaile
Best Answer
Level 30

Here is an option using union:

$drawing_query = Drawing::where('published', 1)->select(['name', 'creation_date']);
$animations_query = Animations::where('published', 1)->select(['name', 'creation_date']);

$creations = $drawing_query->union($animations_query)->orderBy('creation_date', 'desc')->limit(4)->get();

Please note that I am selecting the same columns for both queries. creation_date is the only mandatory column since it is used to order the results. I have added a column called name as an example.

Please or to participate in this conversation.