Implementing One-to-Many Relationship in Laravel Eloquent

62 Views Asked by At
  • I'm working on a Laravel project and I'm trying to set up a one-to-many relationship between two models

  • How can I create a new user and associate multiple posts with that user using Eloquent?

  • How do I retrieve all posts belonging to a specific user?

Here's a code of my 'User' and 'Post' models:

// User.php
class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}
// Post.php
class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
  • I expected to be able to create a new user and associate multiple posts with that user using Eloquent, I anticipated being able to retrieve all posts belonging to a specific user through the established relationship
1

There are 1 best solutions below

0
Abdulla Nilam On BEST ANSWER

First, create a table for post. It should look like this.

In migration file

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('user_id');
    $table->string('title');
    $table->text('body');
    $table->timestamps();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});

Create a User and post. (if not exist)

$user = User::create(['name' => 'John Doe', 'email' => '[email protected]', 'password' => Hash::make('password')]);

$post1 = new Post(['title' => 'First', 'body' => 'Content 1']);
$post2 = new Post(['title' => 'Second', 'body' => 'Content 2']);

$user->posts()->saveMany([$post1, $post2]);

In controller

$user = User::find($userId);  // created user ID
$posts = $user->posts; 

Or

$user = User::with('posts')->find($userId); # recommended. Cz it uses a single query

You can use Laravel factories or Laravel Tinker to create dummy data