0

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');
    }
}
schutte
  • 1,949
  • 7
  • 25
  • 45
  • Possible duplicate of [Select specific columns from Eloquent relations](https://stackoverflow.com/questions/32727060/select-specific-columns-from-eloquent-relations) – Collin Oct 23 '19 at 11:25
  • @Collin I think this is not duplicate to that, bdw you can review it if its really duplicate, 've been there to that link before I ask question. – schutte Oct 23 '19 at 11:27

1 Answers1

1

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');
}
Matthias S
  • 3,358
  • 3
  • 21
  • 31