Skip to content

Relationship in Laravel

Reading Time: 2 minutes

Laravel Relationship

Laravel is a modern MVC platform that creates our project with all essential modern tools such as Bootstrap, Unit Test, Blade Template Engine, PSR Standards, ORM Queries  and so on. Working with Laravel is always gives me a breezy experience because of its Eloquent ORM.

Create and use a Laravel Relationship is an easy task,Whether you are on small todo application or a big scale bank project.

In laravel 5.0 there is the following laravel relationship methods are seems:

  • One To One
  • One To Many
  • Many To Many
  • Has Many Through
  • Polymorphic Relations

laravel

One To One

One-to-One relationship is very basic and simple relationship that relates 2 table fields with a single index.

For Example:
Author Table: author_id, name
Contact Table: contact_id, author_id, phone, email

class Author extends Model {

public function contact()
{
return $this->hasOne('App\Contact');
}

}

Inverse Relationship

class Contact extends Model {

public function author()
{
return $this->belongsTo('App\Author');
}

}

One To Many

One To Many is a relationship, that one table field relates with Many Records in another table.
Author Table: author_id, name
Book Table: book_id, author_id, book_title, book_price

class Author extends Model {

public function book()
{
return $this->hasMany('App\Book');
}

}

Many To Many

Many-to-many is a relationship that one table relates by more table. For Example,
Book Table: book_id, author_id, book_title, book_price
CategoryTable: cat_id, cat_description
Book_category Table: cat_id, book_id

class Book extends Model {

public function category()
{
return $this->belongsToMany('App\Book_Category');
}

}

Has Many Through

Has many through relation offers a easy method to access distant relations via an intermediate relation.
Book Table: book_id, author_id, book_title, book_price
CategoryTable: cat_id, cat_description
Book_category Table: cat_id, book_id

class Book extends Model {

public function category()
{
return $this->hasManyThrough('App\Book_Category', 'App\Category');
}

}

Polymorphic Relations

Polymorphic relationship allow a model to belong to more than one other model, on a single association.
For example, you might have a genre model that belongs to either a author or book model.

See also  Advanced PHP Tools