schutte
schutte

Reputation: 2166

How to select specific column in eloquent relationship inside the Model?

EDITED: Guys can you review your suggested duplicate? I did some research before I ask this question, and I'm already to that link, that is not the answer that I'm looking for.


How can I pluck specific column in eloquent relationship? I want only name column to be returned when I Student::find()->subject;

I tried the below codes but doesn't work and returns me an error

App\Student::subject must return a relationship instance.

class Student extends Model
{
    protected $table = 'subjects';
    protected $fillables = ['id', 'name', 'gender', 'birthdate', etc.];

    public function subject()
    {
        return $this->hasMany('App\Subject')->pluck('name');
    }
}

Upvotes: 0

Views: 195

Answers (1)

Matthias S
Matthias S

Reputation: 3563

You can use any query builder functions on the relation. Use select to only select the name column

public function subject()
{
    return $this->hasMany('App\Subject')->select('name');
}

Upvotes: 1

Related Questions