Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: How to automatically fetch relations when serializing through toArray/toJson

I figures this works for automatically fetching user and replies when I am serializing my object to JSON, but is overriding toArray really the proper way of doing this?

<?php  class Post extends Eloquent {     protected $table = 'posts';     protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');      public function user()     {         return $this->belongsTo('User');     }      public function replies()     {         return $this->hasMany('Post', 'parent_post_id', 'id');     }      public function toArray()     {         $this->load('user', 'replies');         return parent::toArray();     } } 
like image 664
Ronni Egeriis Persson Avatar asked Feb 05 '14 22:02

Ronni Egeriis Persson


1 Answers

Instead of overriding toArray() to load user and replies, use $with.

Here's an example:

<?php  class Post extends Eloquent {     protected $table = 'posts';     protected $fillable = array('parent_post_id', 'user_id', 'subject', 'body');      protected $with = array('user', 'replies');       public function user()     {         return $this->belongsTo('User');     }      public function replies()     {         return $this->hasMany('Post', 'parent_post_id', 'id');     }  } 

Also, you should be using toArray() in your controllers, not your models, like so:

Post::find($id)->toArray(); 

Hope this helps!

like image 190
Jake Avatar answered Sep 24 '22 03:09

Jake