byronsmith's avatar

Let Join Column names

Hi All.

Does anyone know how to deal with Left Joins and column names that are returned?

i.e i have an left join, both tables have the column name, title. I was hoping eloquent would return table1.title and table2.title, but it doesn't, it simply returns title and therefore overwrites the other in the returned array.

Can I force eloquent to return the table names in the return results?

0 likes
9 replies
jlrdw's avatar

Have you read the docs on query builder, it has examples.

byronsmith's avatar

Hi @jlrdw

I have and its suggesting I use select('table.name') or select('table.name as foobar') which is just not going to work for me as I have a ton of columns. I would really like all the columns returned in table.column notation. Besides, when you do select('table.name') it still only returns 'name' in the array. I have multiple columns called 'name' in my join.

Unless you're talking about some other examples I have not read. can you point me in the right direction please?

byronsmith's avatar

Hi @arnabrahman

Thanks for the reply, but that still only returns the columns names by themselves and not table.column notation.

What if I want to return table1.* and table2.* while both tables have the column called, 'name' configured.

All I will get is is a single element called name. I need two elements called table1.name and table2.name

byronsmith's avatar

Hi @jldw

I understand how to do joins, my question is related to the column names in the returned results.

Let me try simplify it.

db tables

users
id
name

cars
id
name
users_id

query

$output = DB::table('users')->leftJoin('cars', 'users.id', '=', 'cars.users_id')->get();

The results that will be returned will be:

array (
    id
    name
    users_id
)

as you can see there is only one 'name' returned. however what I would like is:

array (
    users.id
    users.name
    cars.id
    cars.name
    cars.users_id
)

Hope this clears things up.

1 like
arnabrahman's avatar
Level 1

@byronsmith I'm not sure you can do that or not. I use 'as' to specify the conflicted columns.

1 like
byronsmith's avatar

I was hoping it would not come to that :) it looks to be a database 'feature' and not to be laravel specific .

We have resorted to prefixing our column names with an identifier instead of using AS, which is sort of the same thing but at least it's hard set.

Thanks for your input and help. I really do appreciate it.

1 like
JonathanAspeling's avatar

9 Years later and also wrestling with this - current theory is to use a name generating algo to generate the column names with table prefix strings and then injecting that into the Select method - still digging for more but looks like in 2025 this is still a limitation that SQL auto prefixes duplicate column names and in the object construction it automatically tries to merge.

Please or to participate in this conversation.