Web Design Company in Mumbai, India and North Carolina, USA
Laravel One to Many Eloquent Relationship Tutorial with Example

Laravel One to Many Eloquent Relationship Tutorial with Example

February 15, 2023
Written By Sumeet Shroff

Web Design & Creative

I'm happy to guide you through the One-to-Many Eloquent Relationship in Laravel. This tutorial will help you understand how to establish a One-to-Many relationship in Laravel using Eloquent models. First, we need to define the two models that we'll be working with: the "User" model and the "Post" model. We'll start by creating a migration for the "users" table:

php artisan make:migration create_users_table --create=users

We'll define the schema for the "users" table in the migration file:

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Next, we'll create the "Post" model and migration:

php artisan make:model Post -m

The "-m" option tells Laravel to also create a migration for the "posts" table. We'll define the schema for the "posts" table in the migration file:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->foreignId('user_id')->constrained();
    $table->timestamps();
});

Note that we've added a "user_id" foreign key to the "posts" table, which will reference the "id" field of the "users" table. This is how we establish the One-to-Many relationship between the two tables. Now that we've defined the models and migrations, we can move on to defining the relationship between the two models. We'll start by defining the relationship in the "User" model:

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

Here, we're using the "hasMany" method to define a One-to-Many relationship between the "User" and "Post" models. This means that a user can have many posts. Next, we'll define the inverse relationship in the "Post" model:

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Here, we're using the "belongsTo" method to define the inverse of the One-to-Many relationship between the "User" and "Post" models. This means that a post belongs to a single user. With the relationships defined, we can now use them to retrieve data. For example, to get all the posts for a given user, we can do:

$user = User::find(1);
$posts = $user->posts;

This will retrieve all the posts for the user with an ID of 1. To create a new post for a user, we can do:

$user = User::find(1);
$post = new Post();
$post->title = 'New Post';
$post->content = 'This is the content of the new post.';
$user->posts()->save($post);

This will create a new post with a title and content, and associate it with the user with an ID of 1. To retrieve the user for a given post, we can do:

$post = Post::find(1);
$user = $post->user;

This will retrieve the user who created the post with an ID of 1. In conclusion, the One-to-Many Eloquent Relationship in Laravel is an essential aspect of building applications. It allows us to associate multiple records of one table with a single record of another table, making it easier to query and manage related data. To summarize, we started by creating migrations for the "users" and "posts" tables and defining their schema. We then created models for the "User" and "Post" and defined the One-to-Many relationship between them using the "hasMany" and "belongsTo" methods. Finally, we used these relationships to retrieve and create data for the two models. It's worth noting that Laravel also supports other types of Eloquent relationships, such as One-to-One, Many-to-Many, and Polymorphic. These relationships allow us to build more complex and dynamic applications, and it's important to understand how they work. Overall, the One-to-Many Eloquent Relationship in Laravel is a powerful feature that can help simplify the process of working with related data in our applications. With a good understanding of how it works, we can build more efficient and effective applications.

Sumeet Shroff

Sumeet Shroff

Loading...