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

eloquent, laravel, laravel-4, php

Solution

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!

Problem

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(); } } ```

Original source