Search code examples
phplaraveleloquentilluminate-container

Eloquent ORM object relashionship


i have two tables. School and Student.

When i fetch all Students

Student::all()->toJson();

I get a response with

[
  {
    "id": 1,
    "school_id": 1,
    "name": "Jhon"
  }
]

But actually i would like to receive

[
  {
    "id": 1,
    "school": {
        "id": 1
    },
    "name": "Jhon"
  }
]

I know i could do

Student::with(['school']);

But then it do an extra query to school table, which is not necessary, as i only need the school id, and not all other attributes.


Solution

  • You can override the toArray method in your model. The same thing also would be possible with toJson, but toArray gets called by toJson and in my opinion its nicer to do such stuff in toArray

    class Student extends Eloquent {
    
        public function toArray($options = 0){
            $this->school = ['id' => $this->school_id];
            unset($this->school_id);
    
            return parent::toArray($options);
        }
    }
    

    Edit

    To keep the model the same and only change to output (which is probably better)

    public function toArray($options = 0){
        $array = parent::toArray($options);
        $array['school'] = ['id' => $array['school_id']];
        unset($array['school_id']);
        return $array;
    }