Ask Your Question
3

What is the method for including alias in Laravel's eager loading for a select query?

asked 2023-05-29 08:23:22 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-29 08:48:02 +0000

ladyg gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-29 08:23:22 +0000

Seen: 11 times

Last updated: May 29 '23