Laravel one to many relationship

Laravel one to many relationship

In this article let’s understand one-to-many relationship in Laravel.

Laravel provides many relationship to work with multiple tables and the very basic one is one-to-many relationship.

So, when one record of the table is associated with many records of another table but another tables one record will only be associated with only record from first table.

Check below graphics to understand it in simple scenario.

What you can see from graphics is one user can have many posts but one post can only belong to one user.

Let’s understand it through example where we have:

  • Two models : Author and Post (we will use author as user)
  • Two migrations: For Author and Post

Create them using below artisan command :

php artisan make:model Author -m
php artisan make:model Posts -m

This will create two models and two migrations as below:

app/Models/
    Author.php
    Post.php

database/migrations/
    ***_create_authors_table.php
    ***_create_posts_table.php

Open ***_create_authors_table.php and modify as blow:

public function up(): void
    {
       Schema::create('authors', function (Blueprint $table) {
          $table->id();
          $table->string("name");
          $table->string("email");
         $table->timestamps();
       });
    }

Check ***_create_posts_table.php and modify as blow:

public function up(): void
    {
       Schema::create('posts', function (Blueprint $table) {
           $table->id();
           $table->unsignedBigInteger('author_id');
           $table->string("title");
           $table->text("text");
           $table->timestamps();
       });
    }

Open app/Models/Author.php and modify as blow:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Author extends Model
{
    use HasFactory;
    public function posts()
    {
        return $this->hasOne(Post::class);
    }
}

Check app/Models/Post.php and modify as blow:

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;
    public function author()
    {
        return $this->belongsTo(Author::class);
    }
}

A relationship between a Author model and a Post model will be the hasMany method, while a relationship between a Post model and a Author model will be the belongsTo method.

Run Migrations:

php artisan migrate

Use below methods in your controller to check how one-to-many relationship works:

/* Create */
$author= new Author([
    'name' => 'CSP',
    'email' => 'codingsolutionspoint@gmail.com'
]);
$author->save();

/* Create multiple posts for the author */
$author->posts()->createMany([
    ['title' => 'First Post', 'text' => 'This is the content of the first post.'],
    ['title' => 'Second Post', 'text' => 'This is the content of the second post.'],
]);

/* fetch posts */
$author= Author::find(1);
$posts = $author->posts;
foreach ($posts as $post) {
    echo $post->title . ': ' . $post->text. "\n";
}

/* fetch author */
$post= Post::find(1);
$author = $post->author;
echo $author->name; // Output: CSP

That’s it on Laravel one to many relationship. Hope this finds you helpful.

See other articles on Laravel here.