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.
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.
Users Table
Users Phone No Table
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.
Users Table
UserPhoneNo Table
Here we have created relation with hasMany as user gonna have many phone no.
Same as in user model here we have created relation with belongsTo because phone no gonna be belongs to user.
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
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
In the above example, we have established a One-to-Many relationship between the users table and the user_phone_nos table.
This setup follows best practices in Laravel and allows you to efficiently manage and retrieve related data.