Laravel Relationship with Comma Separated Values

Websolutionstuff | Dec-10-2024 | Categories : Laravel PHP

In this post, I’ll show you how to set up relationships with comma-separated column values in a Laravel application. Sometimes, we store IDs in a column as comma-separated values, but when it comes to fetching related data from another table, establishing a relationship can be tricky. That’s where the ghanuz/relations package comes in handy.

To explain this, I’ll create two tables: products and colors. When adding a product, we’ll store the associated color IDs in a comma-separated column.

Then, I’ll demonstrate how to use Laravel relationships to retrieve the color details effortlessly. This approach is perfect for handling legacy databases or unconventional data structures in Laravel projects.

Laravel Relationship with Comma Separated Values

 

Step 1: Install Laravel 11

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

composer create-project laravel/laravel example-app

 

Step 2: Install ghanuz/relations

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

composer require ghanuz/relations

 

Step 3: Create Migration

Next, we'll create 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->string("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, 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

We will use FindInSetMany() method for colors relationship.

app/Models/Product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use GhanuZ\FindInSet\FindInSetRelationTrait;

class Product extends Model
{
    use HasFactory, FindInSetRelationTrait;

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

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

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;

    protected $fillable = ["name"];
}

 

Step 5: Create Route

Next, we'll 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, 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:");
        print_r($gold->toArray());
        print_r($gold->colors->toArray());
        print_r("SILVER:");
        print_r($silver->toArray());
        print_r($silver->colors->toArray());
    }
}

 

Step 7: Run Laravel Application

Now, run the laravel application using the following command.

php artisan serve

Output:

GOLD:
Array
(
    [name] => Gold
    [color] => 1,2
    [updated_at] => 2024-11-30T11:27:30.000000Z
    [created_at] => 2024-11-30T11:27:30.000000Z
    [id] => 1
)
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Red
            [created_at] => 2024-11-30T11:27:30.000000Z
            [updated_at] => 2024-11-30T11:27:30.000000Z
        )

    [1] => Array
        (
            [id] => 2
            [name] => White
            [created_at] => 2024-11-30T11:27:30.000000Z
            [updated_at] => 2024-11-30T11:27:30.000000Z
        )

)
SILVER:
Array
(
    [name] => Silver
    [color] => 1,3
    [updated_at] => 2024-11-30T11:27:30.000000Z
    [created_at] => 2024-11-30T11:27:30.000000Z
    [id] => 2
)
Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Red
            [created_at] => 2024-11-30T11:27:30.000000Z
            [updated_at] => 2024-11-30T11:27:30.000000Z
        )

    [1] => Array
        (
            [id] => 3
            [name] => Blue
            [created_at] => 2024-11-30T11:27:30.000000Z
            [updated_at] => 2024-11-30T11:27:30.000000Z
        )

)

 


You might also like:

Recommended Post
Featured Post
Python Read CSV File Without Header
Python Read CSV File Without H...

In this article, I'll show you how to read CSV files without a header in Python. Sometimes, CSV files don't have...

Read More

Sep-20-2024

Laravel 11 Create CRUD Operation with Database
Laravel 11 Create CRUD Operati...

Hello developers! In this article, we'll learn about Laravel 11 to create Creat Reas Update Delete operations w...

Read More

Apr-08-2024

How to Install Material Theme in Angular 17
How to Install Material Theme...

In this article, we'll install the material theme in angular 17. Material Theme brings a polished design and us...

Read More

Mar-29-2024

How To Get Current Date And Time In Node.js
How To Get Current Date And Ti...

In this example we will see how to get current date and time in Node.js application. In Node.js date and time are handle...

Read More

Sep-01-2021