How to implement a self referencing (parent_id) model in Eloquent Orm

eloquent, laravel, php

Solution

I had some success like this, using your exact DB table.

User Model:

class User extends Eloquent {

    protected $table = 'users';
    public $timestamps = false;

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

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

}

and then I could use it in my code like this:

$user     = User::find($id);

$parent   = $user->parent()->first();
$children = $user->children()->get();

Give that a try and let me know how you get on!

Problem

I have a `User` table and need to allow for users to have a parent user. the table would have the fields: - `id` - `parent_id` - `email` - `password` How would I define this self referencing relationship in Eloquent ORM?

Original source