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(); } }
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With