Did you ever think about using an alias in the select columns while using Laravel Eloquent?. We cannot say it’s very Laravel specific, rather a MySql feature. Basically, when you join two or more tables in MySql, chances are very high that you will have the same column names multiple times in the result. This will throw an ambiguous column error in MySql.
So as a solution we will use as
keyword in the MySql to create aliases for the columns.
This is very true for Laravel’s eloquent as well. You can use the Select column alias in Laravel Eloquent.
For example, you have two tables users and groups, and both have common fields like the name. So how is your query will look like
User::select('users.name as user_name','groups.name as group_name as group_name) ->join('groups', 'users.group_id', '=', 'groups.id')
- Just want to thank us? Buy us a Coffee
- May be another day? Shop on Amazon using our links.
Your prices won't change but we get a small commission.
Leave a Reply