Laravel One to Many Relationship Tutorial

So in this tutorial, we will learn how to apply for one to many relationships, here you will have several tables from which we can connect one table to many other tables.

One to many relationships are used to define relationships where one model contains any amount of another model and one to many relationship is most important part of laravel web application.

In this example, I have created a "posts" table and a "categories" table. To create this kind of relationship in Laravel we have to create two migrations for our posts and categories table.

Laravel One to Many Relationship Tutorial

Step 1 : Create Migrations

Now we have to create migration of "posts" and "sub_categories" table. we will also add foreign key with posts table. so let's create like as below code

posts table migration:

Schema::create('posts', function (Blueprint $table) {

    $table->increments('id');
    $table->string("title");
    $table->string("description");
    $table->integer('category_id')->unsigned();
    $table->timestamps();
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');

});

categories table migration:

 

Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string("name"); $table->timestamps(); });

Step 2 : Create Models

Here, we will create a post and category model. We will also use the "hasMany ()" and "belongsTo ()" methods to connect both models.

Goto App\Models\Post.php and edit bellow code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Models\Category;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function categories()
    {
        return $this->belongsTo(Category::class);
    }
}

Goto App\Models\Category.php and edit bellow code

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use App\Models\Post;

class Category extends Model
{
    /**
     * Get the post for the blog post.
     */
    public function post()
    {
        return $this->hasMany(Post::class);
    }
}

Step 3 : Create Controller

if no have a PostController then mack bellow command

php artisan make:controller PostController

Goto app/Http/Controllers/PostController.php and follow below code

Get Category Items

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $posts = Post::find(1);
		$categories = $posts->categories;
    	dd($categories);
    }
}

Find Post Items

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use App\Models\Category;

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $category = Category::find(1);
		$post = $category->post;
    	dd($post);
    }
}

One To Many Relationship with Query

$categories = Post::find(1)->categories()
                    ->where('name', 'like', '%laravel%')
                    ->get();
dd($categories);

Add Category using Model

$post = Post::find(1);
 
$category = new Category;
$category->name = "laravel";
 
$post->categories()->save($category);

I hope this will help you to understand one to many eloquent relationship.

All Laravel relationship TUtorials

Laravel One to Many Relationship Tutorial