Laravel 9 One to Many Relationship Example

By Guest | Apr 21, 2022 | Laravel
Share :

https://www.fundaofwebit.com/post/laravel-9-one-to-many-relationship-example

Laravel one to many relationship example; In this tutorial, you will learn laravel one to many relationship with examples.

Using one to many relationship, you can perform crud (create, read, update, delete) operation with the eloquent model from the database table in laravel.

Laravel Eloquent One to Many Relationship Example


In this tutorial, we will be learning belongsTo Relationship and hasMany relationship in laravel 9.

Let's take an example of Category and Products for this one to many relationship.


Step 1: Create 2 migration tables named "categories" and "products" as follows:


Create Categories table migration with following command: 

php artisan make:migration create_categories_table

after successfully creating the migration, paste the below code:

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


Create Products table migration with following command: 

php artisan make:migration create_products_table

after successfully creating the migration, paste the below code with foreign key setup. 

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('category_id');
    $table->string('name');
    $table->string('price');
    ...
    ...
    $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
    $table->timestamps();
});


Step 2: Define One to Many Relationship

Create 2 models named Category and Product as follows:

Create Category Model with following command:

php artisan make:model Category

after successfully creating the model, give the hasMany() Relationship Product in Category model as given below:

<?php

namespace App\Models;

use App\Models\Product;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Category extends Model
{
    use HasFactory;

    protected $table = 'categories';

    protected $fillable = [
        'name',
        ...,
        ...
    ];

    public function products()
    {
        return $this->hasMany(Product::class, 'category_id', 'id');
    }
}


Create Product Model with following command:

php artisan make:model Product

after successfully creating the model, give the belongsTo() Relationship in laravel. Which explains that, this product belongs to a particular category. 

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $table = 'products';

    protected $fillable = [
        'category_id',
        'name',
        'price',
        ...
    ];

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }
}


Step 3: Retrieving Data - hasMany() Relationship (One to Many)

Once relationship is defined, as given in Step 2, we can get/retrieve data from database using Eloquent model.


Example 1: get all products data of a particular category with Eloquent Model: 

get category data from controller as given below:

public function viewCategory($category_id)
{
    $category = Category::find($category_id);
    return view('category-view', compact('category'));
}

display all products of particular category in category-view.blade.php file as given below:

@extends('layouts.app')

@section('content')

    <div class="container">
        <div class="row">
            <div class="col-md-12">
               
                <h4>Products</h4>
                <div class="breadcrum alert alert-info">
                    <h6> Home / {{ $category->name }} / Products</h6>
                </div>
                <div class="row">

                    @if(count($category->products) > 0)
                        @foreach ($category->products as $product)
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-body">
                                    <h4> {{ $category->name }} </h4>
                                    <h4> {{ $category->price }} </h4>
                                </div>
                            </div>
                        </div>
                        @endforeach
                    @endif
                   
                </div>
               
            </div>
        </div>
    </div>

@endsection


Example 2: get all products data of a particular category with Eloquent Model: 

public function viewCategory($category_id)
{
    $products = Category::find($category_id)->products()->get();
    return view('category-view', compact('products'));
}

display all products of particular category in category-view.blade.php file as given below:

@extends('layouts.app')

@section('content')

    <div class="container">
        <div class="row">
            <div class="col-md-12">
               
                <h4>Products</h4>
                <div class="row">

                    @foreach ($products as $product)
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <h4> {{ $category->name }} </h4>
                                <h4> {{ $category->price }} </h4>
                            </div>
                        </div>
                    </div>
                    @endforeach
                   
                </div>

            </div>
        </div>
    </div>

@endsection


Example 3: get all products data of a particular category with Eloquent Model: 

public function viewCategory($category_id)
{
    $category = Category::find($category_id);
    $products = $category->products;
    return view('category-view', compact('category','products'));
}

display all products of particular category in category-view.blade.php file as given below:

@extends('layouts.app')

@section('content')

    <div class="container">
        <div class="row">
            <div class="col-md-12">
               
                <h4>Products</h4>
                <div class="breadcrum alert alert-info">
                    <h6> Home / {{ $category->name }} / Products</h6>
                </div>
                <div class="row">

                    @foreach ($products as $product)
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-body">
                                <h4> {{ $category->name }} </h4>
                                <h4> {{ $category->price }} </h4>
                            </div>
                        </div>
                    </div>
                    @endforeach
                   
                </div>

            </div>
        </div>
    </div>

@endsection


Step 4: Retrieving Data - belongsTo() Relationship (Inverse of One to Many)

Once relationship is defined, as given in Step 2, we can get/retrieve data from database using belongsTo Eloquent model.

Inverse of One to Many Relationship in laravel.


Example 1: get category data of particular product:

public function viewProduct($product_id)
{
    $product = Product::find($product_id);
    return view('product-view', compact('product'));
}

display products with it's category data in product-view.blade.php using belongsTo Relationship file as given below:

@extends('layouts.app')

@section('content')

    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <h4>Product View</h4>
                <div class="breadcrum alert alert-info">
                    @if($product->category)
                    <h6> Home / {{ $product->category->name }} / {{ $product->name }}</h6>
                    @endif
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body">
                                <h4> {{ $product->name }} </h4>
                                <h4> {{ $product->price }} </h4>
                            </div>
                        </div>
                    </div>
                </div>
               
            </div>
        </div>
    </div>

@endsection


Example 2: get category data of particular product:

public function viewProduct($product_id)
{
    $products = Product::find($product_id)->category;
    return view('product-view', compact('products'));
}


Example 3: get category data of particular product:

public function viewProduct($product_id)
{
    $products = Product::find($product_id);
    $category = $products->category;
    return view('product-view', compact('category','products'));
}


Example 4: get specific category column value:

public function viewProduct($product_id)
{
    $products = Product::find($product_id);
    $category_name = $products->category()->name;
    return view('product-view', compact('category_name','products'));
}


Step 5: Inserting Data (using of One to Many)


Example 1: Save product data in laravel

public function saveProduct(Request $request, $category_id)
{
    $category = Category::find($category_id);

    $product = new Product;
    $product->name = $request->name;
    $product->price = $request->price;

    // Saving related model
    $category->product()->save($product);
}


Example 2: Save product data in laravel

public function saveProduct(Request $request, $category_id)
{
    $category = Category::find($category_id);
    $category->product()->create([
        'name' => $request->name,
        'price' => $request->price
    ]);
}


Step 6: Delete Data (using of One to Many)


Product Delete

Delete data of product as follows: (This only deletes product data)

Note: This will delete only specific product data.

Example 1:

public function destroy($category_id)
{
    $category = Category::find($category_id);
    $category->product()->delete();
    return redirect('students')->with('message','Daleted Successfully');
}

Example 2: 

public function destroy($product_id)
{
    Product::find($product_id)->delete();
    return redirect('students')->with('message','Daleted Successfully');
}



Category Delete

Delete data of category as follows: 

Note: This will delete category with all its related products.

Example 1: 

public function destroy($category_id)
{
    Category::find($category_id)->delete();
    return redirect('students')->with('message','Daleted Successfully');
}

this above code will delete category data with all its related products.


Example 2: In case, if you have not given/assign the foreign key in products table. use this given below method to delete data conditionally as follows.

public function destroy($category_id)
{
    $category = Category::find($category_id)->product()->delete();
    $category->delete();
    return redirect('students')->with('message','Daleted Successfully');
}


Thank you.

https://www.fundaofwebit.com/post/laravel-9-one-to-many-relationship-example

Share this blog on social platforms