Skip to content
Advertisement

How do I convert SQL statement with alias in a valid Laravel query builder?

I am working on a Laravel 8 application. I have the flowing SQL statement containing the alias country for the column name of the countries table:

SELECT users.first_name, users.last_name, countries.name as country FROM users LEFT JOIN countries ON countries.id = users.country_id

I have used this online tool to convert it to a valid Laravel query builder.

The problem

Unfortunately, the result (visible below), ignores the alias and displays the colum as name instead of country:

DB::table('users')
    ->leftJoin('countries','users.country_id','=','countries.id')
    ->select('users.first_name','users.last_name','countries.name')
    ->get();
How do I fix this problem?

Advertisement

Answer

Try that

DB::table('users')
    ->leftJoin('countries','users.country_id','=','countries.id')
    ->select('users.first_name','users.last_name','countries.name as country')
    ->get();
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement