How to create self referential relationship in laravel?

You can add a relation to the model and set the custom key for the relation field.

Update:

Try this construction

class Post extends Eloquent {

    public function parent()
    {
        return $this->belongsTo('Post', 'parent_id');
    }

    public function children()
    {
        return $this->hasMany('Post', 'parent_id');
    }
}

Old answer:

class Post extends Eloquent {

    function posts(){
        return $this->hasMany('Post', 'parent_id');
    }
}

Leave a Comment