Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To include an alias in Laravel's eager loading for a select query, you can use the selectRaw method:

$users = User::with(['posts' => function($query) {
  $query->select('title as post_title', 'content');
}])->selectRaw('id, name as user_name')->get();

In this example, we are eager loading the posts relationship for User model, but we only want to select the title column from posts table as post_title. We use the selectRaw method to select the id and name column from users table while also using an alias for name as user_name.