Laravel eloquent relationships


In laravel you can define all kind of relationships between database tables on the model itself (as in laravel, model is representation of database table), so here's list of eloquent relationships that you can use in laravel model.

One to One
For one to one relationship, you can use hasOne and belongsTo.
return $this->hasOne('model_name');

return $this->hasOne('model_name', 'foreign_key');

return $this->hasOne('model_name', 'foreign_key', 'local_key');
return $this->belongsTo('model_name');

return $this->belongsTo('model_name', 'local_key');

return $this->belongsTo('model_name', 'local_key', 'parent_key');
One to Many
For one to many relationship, you can use hasMany and belongsTo.
return $this->hasMany('model_name');

return $this->hasMany('model_name', 'foreign_key');

return $this->hasMany('model_name', 'foreign_key', 'local_key');
return $this->belongsTo('model_name');

return $this->belongsTo('model_name', 'local_key');

return $this->belongsTo('model_name', 'local_key', 'parent_key');

Many to Many
For many to many relationship, you can use belongsToMany.
return $this->belongsToMany('model_name');

return $this->belongsToMany('model_name', 'pivot_table_name');

return $this->belongsToMany('model_name', 'pivot_table_name', 'id1', 'id2');

Has many through
The has many through is similar to hasMany but the relation is involving third table.
return $this->hasManyThrough('Post', 'User');
return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');

Polymorphic relations 
Polymorphic relations allow a model to belong to more than one other model, on a single association. You can use morphTo and morphMany.
class Photo extends Eloquent {

    public function imageable()
    {
        return $this->morphTo();
    }

}

class Staff extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}

class Order extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}

Many to many polymorphic relation
In addition to traditional polymorphic relations, you may also specify many-to-many polymorphic relations. You can use morphToMany and morphedByMany.
class Post extends Eloquent {

    public function tags()
    {
        return $this->morphToMany('Tag', 'taggable');
    }

}
class Tag extends Eloquent {

    public function posts()
    {
        return $this->morphedByMany('Post', 'taggable');
    }

    public function videos()
    {
        return $this->morphedByMany('Video', 'taggable');
    }

}
All of these relationships works on laravel 4 and laravel 5
Latest


EmoticonEmoticon