How to alias a table in Laravel Eloquent queries (or using Query Builder)?
To alias a table in a Laravel Eloquent query, you can use the as
method on a DB
facade. Here is an example:
<?php
$users = DB::table('users as u')
->select('u.id', 'u.name')
->get();
This will select all id
and name
columns from the users
table, and alias the table as u
.
You can also use the DB::raw()
method to specify a raw expression in the select clause:
<?php
$users = DB::table('users as u')
->select('u.id', 'u.name', DB::raw('COUNT(posts.id) as post_count'))
->leftJoin('posts', 'u.id', '=', 'posts.user_id')
->groupBy('u.id', 'u.name')
->get();
This will select all id
and name
columns from the users
table, and also a post_count
column that contains the number of posts written by each user (calculated using a left join and a group by clause).
If you want to use the Query Builder instead of the DB
facade, you can use the alias
method:
<?php
$users = DB::table('users')
->alias('u')
->select('u.id', 'u.name')
->get();
This will produce the same result as the first example.