Laravel join overwriting field names

It’s a really common thing to do with databases, join a tables with an other table, but when you have two models that have a field with the same name by default one will overwrite the other!

Let’s take a very simple example, you have two models in Laravel, one called parent and one called child.

If you do the following join to get all the parents and children records into a collection :

Parent::join('children', 'parents.id','=','parent_id')
->get();

You will end up with just one name field (the child one) in your collection.

The key to fixing this isn’t as obvious as you may think, I expected to fix it in the join with some kind of MySQL ‘as’ statement.

To fix this join you would do an as in the select:

Parent::join('children', 'parents.id','=','parent_id')
->select([
   'parents.name as parent_name',
   'children.name as child_name',
   Any other fields you need
])
->get();

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.