Laravel Save Json Array To Database Example

Hello Artisan,

In this tutorial, you will learn how to store an array in the database laravel. I explained simply the step-by-step laravel store array field in the database. Here you will learn how to store array data in the database in laravel. I explained simply how to store the array in the database laravel.

You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 versions. Many times we need to store array data in the database. So I am here to show you how we can store array field data in laravel application. We will declare the array field as a JSON column and we will save it from the controller.

See the below example and preview image to understand:

 

Step 1: Install Laravel

I am going to start from scratch. So download a fresh Laravel project using the below command:

composer create-project laravel/laravel example-app

 

Step 2: Create Model & Migration

We need a Todo model to save our example data. So create it and update it like below:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTodosTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('todos', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->json('data')->nullable();
            $table->timestamps();
        });
    }

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

 

And update the model like:

App/Models/Todo.php

namespace App\Models;

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

class Todo extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'data' 
    ]; 

    public function setDataAttribute($value)
    {
        $this->attributes['data'] = json_encode($value, true);
    }
}

 

Step 3: Create Route

In the third step, we will create one route for testing. so create one route here.

routes/web.php

use App\Http\Controllers\TodoController;
use Illuminate\Support\Facades\Route;

Route::get('/', [TodoController::class, 'index']);

 

Step 4: Create Controller

In this step, we will create TodoController file and write index() a method to create item records with array and access as an array.

app/Http/Controllers/TodoController.php

namespace App\Http\Controllers;

use App\Models\Todo;

class TodoController extends Controller
{
    public function index()
    {
        $input = [
            'title' => 'Example from codecheef.org',
            'data' => [
                '1' => 'One',
                '2' => 'Two',
                '3' => 'Three'
            ]
        ];
  
        $item = Todo::create($input);
  
        dd($item->data);
    }
}

 

Now run php artisan serve and then you can test by visiting the root url.

 

Read also: Upload Large CSV File using Queue Job Batching in Larave

 

Hope it can help you.

#laravel #laravel-9x