Javatpoint Logo
Javatpoint Logo

Laravel Relationship

An Eloquent relationship is a very important feature in Laravel that allows you to relate the tables in a very easy format.

One to one relationship

One to one relationship provides the one-to-one relationship between the columns of different tables. For example, every user is associated with a single post or maybe multiple posts, but in this relationship, we will retrieve the single post of a user. To define a relationship, we need first to define the post() method in User model. In the post() method, we need to implement the hasOne() method that returns the result.

Let's understand the one to one relationship through an example.

  • First, we add the new column (user_id) in an existing table named as posts. Here, user_id is the foreign key.
Laravel Relationship
  • Migrate the above changes in a database by using the command given below:
    php artisan migrate.
  • After the migration, the structure of the posts table is shown in the below screenshot:
Laravel Relationship

The above screenshot shows that the user_id column is added successfully.

  • Open the User.php file and add the following code in the User.php file.

In the above code, we have implemented the hasOne() method that contains the single argument, i.e., name of the related model. By default, the Post considers the user_id as a foreign key. The post() method searches the posts table as we have mentioned the namespace 'App/Post' and look for the column user_id. We can override this convention by providing a foreign key as a second argument. It can be re-written as:

return $this->hasOne('App\Post',foreign_key)

  • Now, we will add the route in the web.php file.

The above code is finding the user with an id number 1 and then implementing the post to find the post of the user having user_id equal to 1.

Output

Laravel Relationship

Inverse Relation

Inverse relation means the inverse of the one-to-one relationship. In the above, we have retrieved the post belonging to a particular user. Now, we retrieve the user information based on the post. Let's understand this through an example.

  • First, we create the route in the web.php file.
  • Open the Post.php file(model) that we created earlier.

Output

Laravel Relationship

One-to-many relationship

Laravel also provides a one-to-many relationship.

  • First, we define the route that finds out all the posts of a single user.
  • Add the following code in the User.php(model) file.

Output

Laravel Relationship

Many-to-Many relationship

A many-to-many relationship is more complicated than a one-to-one relationship and a one-to-many relationship. To define the many-to-many relationship, we need to create a pivot table. The pivot table is basically a look up table that relates the two tables. For example, a user may have different roles where the roles can be shared by other users, like many users can have the role of 'Admin'. To define the relationship between the users and roles, we need to create the three tables, user, roles, and role_user. In our database, the user table is already created; we need to create two tables, i.e., roles table and pivot table (roles_user).

  • First, we create the Role model. We use the following command to create the model:
    php artisan make:model Role -m
Laravel Relationship

The above screen shows that the roles table has been created. The create_roles_table.php has been created in the database/migration directory. The structure of this file is given below:

In the above code, we have added the new column named as 'name'. The 'name' column defines the name of the role of a user.

  • Now, we have two tables, the roles table, and the users table. To relate these two tables, we need to create the pivot table, roles_user table.
Laravel Relationship

The above screen shows that the roles_user table has been created. The structure of the create_roles_user_table is given below:

In the above code, we have added two new columns, user_id, and role_id.

  • Migrate all the above changes by using the command given below:
    php artisan migrate
Laravel Relationship
  • The below screen shows all the three tables, i.e., roles, roles_user, and users are created.
Laravel Relationship

Data available in the roles table:

Laravel Relationship

Data available in the users table:

Laravel Relationship

Data available in the roles_user table:

Laravel Relationship
  • Now, we define the route.

web.php

  • We add the following code in User.php file which relates both the tables.

In the above code, belongsToMany() method contains two parameters, 'App\Role', which is the namespace to use the Role model, and 'roles_user' is the name of the pivot table that relates two tables. The belongsToMany() method can also be written as:

belongsToMany('App\Role','roles_user','user_id','role_id');

The above line contains two more parameters, user_id, and role_id. The user_id is the foreign key for the users table, and role_id is the foreign key for the roles table.

Output

Laravel Relationship
Laravel Relationship

Accessing the intermediate/pivot table

In many-to-many relationship, we create the pivot or intermediate table. Now, we will see how to retrieve this pivot table.

In the above model, we are retrieving the user having an id equal to 1. Then, using the foreach loop, we are retrieving the role model and assigned in the pivot attribute.

Laravel Relationship

If we want to retrieve the specific column from the pivot table,

web.php

Output

Laravel Relationship

Has Many Through

The 'has many through' relationship provides a convenient way of accessing the distant or intermediate relations. For example, we have three tables, users, posts, and country table. Now, we want to find the posts belonging to that country through the User model.

Let's understand through an example.

  • The country table is not available in the database. We first create the country model with the database migration.
Laravel Relationship
  • Add the 'name' column in country table.
  • Migrate the above changes by using the command given below:
    php artisan migrate
  • Now, we add the new column 'country_id' in users table. Use the command given below:
    php artisan make:migration add_new_column_column_id -table=users;
  • After the execution of the above command, the add_new_column_column_id file is created in database/migrations directory.

In the above code, we have added a new column in users table.

To migrate the above changes in the database,

php artisan migrate

  • Open the country.php(model) file. We are going to pull the posts of a specific country using the country model.
    country.php
  • Now, we add the route that pulls out the posts of a specific country.

Output

Laravel Relationship

Polymorphic relationship

One-to-many (Polymorphic)

The Polymorphic relationship is similar to the one-to-many relationship. When a single model belongs to more than one type of model on a single association is known as one-to-one polymorphic relationship. For example, if we have three tables, posts, users, and photo table, where photo table represents the polymorphic relation with the users and posts table.

Let's understand this relationship through an example.

  • We have already created the users and the posts table in the previous topic. Now, we create a photo table.
Laravel Relationship

Open the create_photos_table.php file created in the migrations folder.

In the above code, we have added three columns, path, imageable_id, and imageable_type. The path determines the path of the image, imageable_id is the id value of the user or post, and imageable_type is the class name of the model.

  • We will delete the user_id column from the posts table, which we have created previously.
  • Look at the database tables.

Data available in a posts table

Laravel Relationship

Data available in users table:

Laravel Relationship

Data available in photo table:

Laravel Relationship
  • Open the Photo model file.
  • Add the following code in the User model file.
  • Add the following code in the Post model file.
  • Now, we will create the routes for both users and posts.

Output

Laravel Relationship
Laravel Relationship

Inverse of one-to-many (polymorphic) relationship

In this topic, we will perform the inverse operation of the one-to-many polymorphic relationship. Till now, we found the image of the users and posts, now we find out the owner of the image.

Let's understand through an example.

We need to create the route in web.php file.

In the above code, Photo::findOrFail($id) method determines whether the photo of a given id exists or not. If exists, then it returns the details of the image through the statement, '$photo->imageable'.

Output

Laravel Relationship

The above output shows the details of the image.

Many-to-many polymorphic relationship

In a many-to-many polymorphic relationship, a target model consists of unique records that are shared among the various models. For example, a tag table shares the polymorphic relation between the videos and the posts table. A tag table consists of the unique list of tags that are shared by both the tables, videos, and the posts table.

Let's understand through an example.

  • First, we create the models with database migration named as Audio, Tag, and Taggable.
Laravel Relationship
  • After creating the models, we will edit their migrated files.

Open the migration file of the Audio table named as 'create_audio_table'.

In the above code, we have created the name column in the audio table by using the command $table->string('name');.

Open the migration file of the Tag model named as 'create_tag_table'.

In the above code, we have created the name column in the tags table by using the command $table->string('name');.

Open the migration file of the Taggable model named as 'create_taggables_table'.

In the above code, we have added three new columns in the taggables table, i.e., tag_id, taggable_id, and taggable_type. The tag_id represents the id of the tag table, taggable id represents the id of the model table, and taggable type represents the name of the class.

  • To migrate the above changes, we use the command given below:
    php artisan migrate
  • Look at the database table:

Data available in an audio table:

Laravel Relationship

Data available in post table:

Laravel Relationship

Data available in tags table:

Laravel Relationship

Data available in taggables table:

Laravel Relationship
  • Now we define the relationship on the model.

Audio.php

Post.php

  • Now we define the route.

Output

When accessing the route of the post, the output would be:

Laravel Relationship

When accessing the route of the audio, the output would be:

Laravel Relationship

Inverse of many-to-many (polymorphic) relationship

In a many-to-many polymorphic relationship, we found the tags belonging to the post and audio model. But, in an inverse relationship of many-to-many (polymorphic), we will find out all the posts and audios that belong to a particular tag.

Let's understand through an example.

  • First, we define the method in a Tag model.

Tag.php

In the above code, we define two methods, posts() and audios(). In the posts() method, we are retrieving all the posts that belong to a specified tag. In the audios() method, we are retrieving all the audios that belong to a specified tag.

  • Now, we define the route.

Output

Laravel Relationship
Laravel Relationship
Next TopicLaravel Tinker




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA