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

Pixelairport's avatar

Eloquent DB Select from different Tables in one call

Hi. I try to make a simple example for my question. I have 3 tables (like video, music, image, ...). Each of the tables has id, name and user_id field. Now when a user logs in, I need to get all media files for the user. At the moment I would do 3 selects and then sort by created_at via helper functions for collections. But is there a way to select 3 tables at once, when tables have the same fields?

Another way would be to make copies in one database, but then I have content doubled in db tables. Not so perfect I think.

And another little problem I think about... Each media (video, music and image) should get a slug like at youtube (e.g. youtube.com/AbcD3F9...). Is this also possible when I have different tables, because I dont want duplicates. I use something like hashids package, but then I would have duplicates. In one table I can say unique() ... is something else possible for multiple tables? Otherwise I could make a prefix like VI for video or MU for Music.

I hope you understand my problem an can help. Thx.

0 likes
1 reply
Snapey's avatar
Snapey
Best Answer
Level 122

if the tables are very similar, you can use a UNION statement to join the table results before returning a collection.

https://laravel.com/docs/10.x/queries#unions

Otherwise its three selections and then merge the collections.

In terms of your final point, you could add a media type column to the database query so that you know which table the row came from and then prefix the unique URL with a code (as you said)

1 like

Please or to participate in this conversation.