phplaraveleloquenteloquent-relationshiplaravel-models

Implementing One-to-Many Relationship in Laravel Eloquent


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);
    }
}

Solution

  • 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' => 'john@example.com', '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