Laravel store array in database example

In this article, we will explain how to store an array in a Laravel database with a step-by-step guide. We will explore how to efficiently save array data in a database using Laravel. This article provide simple solution Laravel store array in database.

Sometimes, when dealing with large data sets or dynamic columns, it’s impractical to create numerous field in a Laravel database. Storing a JSON array can be a simple and effective solution.  This example demonstrates how to store and access a JSON array in a database using Laravel.

First, We will create a migration with a JSON column. Then, we will create a model with getter and setter methods. When creating records, you can pass data as an array, and when retrieving records, the data will be returned as an array. Follow the steps below to achieve this.

Laravel store array in database using following step:

Step 1: Install Laravel

This is optional, however, if you have not created the Laravel app, execute the command below:

composer create-project laravel/laravel example-app

2. Create migration

Here, we need to create a base migration for the ‘tests’ table with ‘detail’ and ‘data’  columns. We will also create a model for the ‘tests’ table. This will allow you to easily store an array in a Laravel database.

php artisan make:migration create_tests_table
Migration file
<?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('tests', function (Blueprint $table) {
            $table->id();
            $table->string('detail');
            $table->json('data')->nullable();
            $table->timestamps();
        });
    }

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

Then run migration command to create tests table.

php artisan migrate
3. Create model

In this step using you can create model. We will create Test.php model with getter setter. let’s create model following example.

<?php

namespace App\Models;

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

class Test extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'detail',
        'data'
    ];
    
    
    protected function data(): Attribute
    {
        return Attribute::make(
        get: fn ($value) => json_decode($value, true),
        set: fn ($value) => json_encode($value),
        );
    }
}
4. Create route

We will create one route for testing. So create one route here. you can use following example method.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

Route::get('test', [TestController::class, 'test']);
5. Create controller

In this step, we will create TestController file and write test() method to create test record with array and get as array.

App/Http/Controllers/TestController.php
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function test()
    {
        $testData = [
            'detail' => 'Test',
            'data' => [
                '1' => 'One test',
                '2' => 'Second test',
                '3' => 'Third test'
            ]
        ];
        
        $test = Test::create($testData);
        
        dd($test->data);
    }
}
Run laravel app:

All the requirement steps have been done for laravel save array from model then you can use bellow command hit enter run the Laravel app.

php artisan serve
Output:

You can see output below like.

array:3 [
    1 => "One test"
    2 => "Second test"
    3 => "Third test"
]

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *