Search code examples
phplaraveleloquentlaravel-5.4eager-loading

Laravel Eloquent - Select Certain Columns Combine with Eager Loading


How to select certain columns on parents table while querying with eager loading?

$accounts = \App\Account::with('status')->get();

Return

[{"id":1,"username":"kuhn.desiree","email":"quentin.gleason@example.net","last_login":"2009-04-02 23:21:20","created_at":"2017-07-15 19:07:03","updated_at":"2017-07-15 19:07:03","status_id":13,"status":{"id":13,"name":"ab","desc":"Quos quas.","created_at":"2017-07-15 19:07:01","updated_at":"2017-07-15 19:07:01"}}]

I only want username and email on Account table.


Solution

  • one way is using select() method

    $accounts = \App\Account::with('status')->select('username', 'email','status_id')->get();
    

    If you would like to retrieve a Collection containing the values of a single column, you may use the pluck method.:

    accounts = \App\Account::with('status')->pluck('username', 'email');