Laravel Relationship with JSON Column

Websolutionstuff | Dec-05-2024 | Categories : Laravel

In this article, I’ll guide you through creating relationships with JSON columns in a Laravel application. Sometimes, we need to store IDs in JSON format, but when fetching related data from another table, how do we establish a relationship with a JSON field? That’s where the staudenmeir/eloquent-json-relations package comes in handy.

To demonstrate, I’ll create two tables: products and colors. We’ll save color IDs in a JSON column when adding a product. Then, I’ll show you how to seamlessly retrieve detailed color information using a Laravel relationship.

Laravel Relationship with JSON Column

Laravel Relationship with JSON Column

 

Step 1: Install Laravel 11

In this step, we'll install the laravel 11 application using the following command.

composer create-project laravel/laravel example-app

 

Step 2: Install staudenmeir/eloquent-json-relations

Next, we'll install the composer package using the following command.

composer require "staudenmeir/eloquent-json-relations"

 

Step 3: Create Migration

Then, we'll create a migration using the following command.

php artisan make:migration create_products_colors_table

Migration:

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

Then, migrate the table into the database using the following command.

php artisan migrate

 

Step 4: Create Models

Next, we'll create a model using the following command.

php artisan make:model Product
php artisan make:model Color

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

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

Now, define the routes into the web.php file.

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

Then, we'll create a controller using the following command.

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

 

Step 7: Run the laravel application

Now, run the laravel application using the following command.

php artisan serve

Output:

Array
(
    [0] => Array
        (
            [id] => 7
            [name] => Red
            [created_at] => 2024-11-23T13:17:30.000000Z
            [updated_at] => 2024-11-23T13:17:30.000000Z
        )

    [1] => Array
        (
            [id] => 8
            [name] => White
            [created_at] => 2024-11-23T13:17:30.000000Z
            [updated_at] => 2024-11-23T13:17:30.000000Z
        )

)
Array
(
    [0] => Array
        (
            [id] => 7
            [name] => Red
            [created_at] => 2024-11-23T13:17:30.000000Z
            [updated_at] => 2024-11-23T13:17:30.000000Z
        )

    [1] => Array
        (
            [id] => 9
            [name] => Blue
            [created_at] => 2024-11-23T13:17:30.000000Z
            [updated_at] => 2024-11-23T13:17:30.000000Z
        )

)

 


You might also like:

Recommended Post
Featured Post
How To Install php-bcmath In Ubuntu
How To Install php-bcmath In U...

In this article, I will guide you through the process of installing php-bcmath on Ubuntu. Php-bcmath is a PHP extension...

Read More

Jul-12-2023

Laravel 9 orWhere Condition Example
Laravel 9 orWhere Condition Ex...

In this article, we will see the laravel 9 orWhere condition example. Where condition is joined together using the ...

Read More

Oct-13-2022

Laravel 9 Custom Helper Function Example
Laravel 9 Custom Helper Functi...

In this article, we will see laravel 9 custom helper function example. As we all know laravel provides many re...

Read More

Mar-07-2022

Laravel 10 Custom Validation Error Message
Laravel 10 Custom Validation E...

In this article, we will see the laravel 10 custom validation error message. Here, we will learn about how to creat...

Read More

May-19-2023