In this post, we will learn how to make Laravel Relationship with Comma Separated Values Example.
Sometimes, we need to store IDs in a comma separated values format. But if we want to get data from another table, how do we create a relationship with a comma separated values field? We can use the `ghanuz/relations` package to solve this problem. In this example, I’ll create two tables:
Laravel Relationship with Comma Separated Values Example
`products` and `colors`. When we add a product, we will save color IDs in a comma separated values column. Then, we’ll retrieve the color details using a Laravel relationship. Let us look at the example below. You Can Learn How to Generate QR Code in Laravel 11?
Let’s see the Laravel Relationship with Comma Separated Values 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 ghanuz/relations
Now, in this step, we will install ghanuz/relations composer package. So, run the following command:
composer require ghanuz/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->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 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 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
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 comma saparated values.
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:");
print_r($gold->toArray());
print_r($gold->colors->toArray());
print_r("SILVER:");
print_r($silver->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:
GOLD:
Array
(
[name] => Gold
[color] => 1,2
[updated_at] => 2024-11-08T04:01:28.000000Z
[created_at] => 2024-11-08T04:01:28.000000Z
[id] => 1
)
Array
(
[0] => Array
(
[id] => 1
[name] => Red
[created_at] => 2024-11-08T04:01:28.000000Z
[updated_at] => 2024-11-08T04:01:28.000000Z
)
[1] => Array
(
[id] => 2
[name] => White
[created_at] => 2024-11-08T04:01:28.000000Z
[updated_at] => 2024-11-08T04:01:28.000000Z
)
)
SILVER:
Array
(
[name] => Silver
[color] => 1,3
[updated_at] => 2024-11-08T04:01:28.000000Z
[created_at] => 2024-11-08T04:01:28.000000Z
[id] => 2
)
Array
(
[0] => Array
(
[id] => 1
[name] => Red
[created_at] => 2024-11-08T04:01:28.000000Z
[updated_at] => 2024-11-08T04:01:28.000000Z
)
[1] => Array
(
[id] => 3
[name] => Blue
[created_at] => 2024-11-08T04:01:28.000000Z
[updated_at] => 2024-11-08T04:01:28.000000Z
)
)
Pingback: Laravel Relationship with Comma Separated Values Example – LearnCodingFree