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
Get User Location using IP Address in Laravel 11
Get User Location using IP Add...

Hello developers! In this article, we'll see how to get user location using an IP address in laravel 11. Here,...

Read More

May-01-2024

How To Preview Image Before Upload In jQuery
How To Preview Image Before Up...

In this article, we will see how to preview an image before uploading it in jquery. You can use the JavaScript...

Read More

Jul-15-2022

How To Remove Spaces Using JQuery
How To Remove Spaces Using JQu...

In this article, we will explain to you how to remove extra space using jquery. many times we have requirements to...

Read More

Aug-10-2020

CRUD With Image Upload In Laravel 10 Example
CRUD With Image Upload In Lara...

In this article, we will see crud with image upload in laravel 10 examples. Here, we will learn how to image upload with...

Read More

Mar-27-2023