In Laravel, a One-to-Many relationship is utilized when one record in a table could have many related records inside another table. This kind of relationship finds many real-life usages. For example, a User can have multiple Phone Numbers.

 

Now, let's see how a One-to-Many relationship between tables can be established, one for the User and another for the User's Phone Number.

Scenario Example

Assume that we have two tables:

Users Table: Contains user details.

User Phone Numbers Table: Contains phone numbers, where each phone number belongs to a user.

 

Step 1: Create Migration Files for Both users and users_phoneno

Users Table

Users Phone No Table

Step 2: Create fields in migration file

Here I create users table with id,name,email,email_verified_at,password and rememberToken fields.

 


 

 

 

 

 

 

 

 

Here I create UserPhoneNo table with id,phone_number and user_id fields in which user_id is foreign id from users table which helps to connect users table.


Step 3: Create Model for Both Users and UserPhoneNo

Users Table

  • php artisan make:model User

UserPhoneNo Table

  • php artisan make:model UserPhoneNo

Step 4: Create One to Many relation in model

  • Users Model

Here we have created relation with hasMany as user gonna have many phone no.


  • UserPhoneNo Table

Same as in user model here we have created relation with belongsTo because phone no gonna be belongs to user.


Step 5: Retrieving Data using One to Many Relationships

So now we have defined relationships, its time to retrieve data which gonna be last step for this process.


Accessing user phone no from user



Accessing user according to phone no


Eager Loading

You can also use eager loading to load the related models efficiently in a single query, which helps reduce the number of queries made to the database.


Accessing user phone no from user



Accessing user according to user phone no



Conclusion

In the above example, we have established a One-to-Many relationship between the users table and the user_phone_nos table.

  • One User can have multiple Phone Numbers.
  • One Phone Number will belong to one User.
  • We have established the relationship in the models using hasMany and belongsTo.
  • We can now fetch phone numbers of a user or a user of a particular phone number using the defined relationships.
  • We also showed how to use eager loading for optimization of queries.

This setup follows best practices in Laravel and allows you to efficiently manage and retrieve related data.