W3docs

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.

To alias a table in a Laravel Query Builder query, you can use the as keyword directly inside the table name string. Here is an example:

How to alias a table in a Laravel Query Builder?

<?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:

Example of DB::raw() method to specify a raw expression in the select clause in a Laravel Query Builder

<?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).

How to alias a table in Laravel Eloquent?

Eloquent shares the same Query Builder under the hood, so you can apply aliases using the from() method or directly in joins:

<?php

use App\Models\User;

$users = User::from('users as u')
  ->select('u.id', 'u.name')
  ->get();

Aliases are especially useful in Eloquent joins to prevent column name conflicts:

<?php

$users = User::join('posts as p', 'users.id', '=', 'p.user_id')
  ->select('users.id', 'users.name', 'p.title')
  ->get();

Note on table prefixes and schema binding: If your application uses database prefixes or multiple schemas, apply the alias after the full table identifier (e.g., 'prefix_users as u' or 'schema_name.users as u'). In complex queries where alias resolution fails, ensure you are referencing the alias consistently in select, where, and join clauses.