Laravel Relationship with JSON Column Example

By Hardik Savani November 6, 2024 Category : Laravel

In this post, we will learn how to make relationship with json column in laravel application.

Sometimes, we need to store IDs in a JSON format. But if we want to get data from another table, how do we create a relationship with a JSON field? We can use the `staudenmeir/eloquent-json-relations` package to solve this problem. In this example, I'll create two tables: `products` and `colors`. When we add a product, we will save color IDs in a JSON column. Then, we’ll retrieve the color details using a Laravel relationship. Let’s look at the example below.

Let's see the example:

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install staudenmeir/eloquent-json-relations

Now, in this step, we will install staudenmeir/eloquent-json-relations composer package. So, run the following command:

composer require "staudenmeir/eloquent-json-relations"

Step 3: Create Migration

In this step, we will create migration for products and colors table. so let's run the following command:

php artisan make:migration create_products_colors_table

next, let's update the migration:

database/migrations/2024_11_04_134601_create_products_colors_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->json("color");
            $table->timestamps();
        });

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

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
        Schema::dropIfExists('colors');
    }
};

Now we need to run migration.

So let's run the below command:

php artisan migrate

Step 4: Create Models

Now, we will create model for products and colors table. so, let's run the following commands and update model.

php artisan make:model Product

php artisan make:model Color

we will use belongsToJson() method for colors relationship.

app/Models/Product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

    protected $fillable = ["name", "color"];

    protected $casts = [
       'color' => 'json'
    ];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function colors()
    {
        return $this->belongsToJson(Color::class, 'color');
    }
}

we will use hasManyJson() method for product relationship.

app/Models/Color.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Color extends Model
{
    use HasFactory;

    use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;

    protected $fillable = ["name"];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function products()
    {
       return $this->hasManyJson(Product::class, 'color');
    }
}

Step 5: Create Route

Here, we will create one route to test relationsihp data. let's update code:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/products', [App\Http\Controllers\ProductController::class, 'index']);

Step 6: Create Controller

Here, we will create ProductController and write index() methos.

1. We will create three color object.

2. Then we will create two products and assign colors as json.

3. get the colors from product object.

php artisan make:controller ProductController

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Color;

class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $red = Color::create(["name" => "Red"]);
        $white = Color::create(["name" => "White"]);
        $blue = Color::create(["name" => "Blue"]);

        $gold = Product::create(["name" => "Gold", "color" => [$red->id, $white->id]]);
        $silver = Product::create(["name" => "Silver", "color" => [$red->id, $blue->id]]);

        print_r($gold->colors->toArray());
        print_r($silver->colors->toArray());
    }
}

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/products

Output:

Array
(
    [0] => Array
        (
            [id] => 7
            [name] => Red
            [created_at] => 2024-11-04T13:53:49.000000Z
            [updated_at] => 2024-11-04T13:53:49.000000Z
        )

    [1] => Array
        (
            [id] => 8
            [name] => White
            [created_at] => 2024-11-04T13:53:49.000000Z
            [updated_at] => 2024-11-04T13:53:49.000000Z
        )

)
Array
(
    [0] => Array
        (
            [id] => 7
            [name] => Red
            [created_at] => 2024-11-04T13:53:49.000000Z
            [updated_at] => 2024-11-04T13:53:49.000000Z
        )

    [1] => Array
        (
            [id] => 9
            [name] => Blue
            [created_at] => 2024-11-04T13:53:49.000000Z
            [updated_at] => 2024-11-04T13:53:49.000000Z
        )

)

I hope it can help you...

Tags :
Shares