Get specific columns using eager loading ('with' function) in Laravel Eloquent

Submitted by orlissenberg - 10 years ago

A variation of http://www.laravel-tricks.com/tricks/column-selection-in-eager-loading Credits: http://stackoverflow.com/questions/16994253/laravel-eager-loading-load-only-specific-columns Warning: this trick does not work on many-to-many relations, see: https://github.com/laravel/framework/issues/2966

class Post extends \Eloquent
{
    
...
    
    public function author()
    {
        $query = $this->hasOne('Your\Name\Space\Author', 'id', 'author_id')
            ->select(['id', 'name']);
    
        return $query;
    }
    
...

}