Get Specific Columns Using Eloquent Relationships In Laravel

Here’s a handy Laravel code snippet which allows you to select specific fields using Laravel’s Eloquent relationships. Lets say we have two tables, users and posts. A user has many posts while the post belongs to single user.

Then, in my User model I can write something like,

public function post(){
        return $this->hasmany('post');
}

This will fetch all the columns from post table that belongs to specific post. However, if you want to summon only a specified columns you can do that using the select method.

public function post(){
        return $this->hasmany('post')->select(['title','slug']);
}

Quick Tip : Set friendly names for validation attributes in Laravel

0 Comments

Leave a Comment.