Laravel 11 Save JSON Data in Database Example

01-May-2024

.

Admin

Laravel 11 Save JSON Data in Database Example

Hi, Dev

In this article, I'll guide you through the process of storing JSON-formatted data into a database within a Laravel 11 application.

JSON (JavaScript Object Notation) stands as a lightweight, human-readable, and machine-parsable data exchange format. Widely employed in web applications, APIs, and system interoperability, JSON simplifies data representation through key-value pairs, akin to JavaScript object literals. Enclosed in curly braces {}, each pair is delimited by commas, with keys as strings and values encompassing strings, numbers, booleans, arrays, or even nested JSON objects.

Sometimes, if we have large data or unfixed columns, then we cannot create too many fields in a database table with the nullable field. So we have to use JSON data type to store values; that way, we can store large data or unstructured data. If you want to store a JSON array in a database in Laravel, then I will give you a simple example of how to store a JSON array, store, and access it from the database in Laravel.

In this demonstration, we'll commence by crafting a migration featuring a JSON column. Subsequently, we'll fashion a model equipped with accessor and mutator methods. During record creation, we'll furnish data in array format, while retrieval operations will yield arrays. Let's delve into a straightforward illustration to grasp this implementation.

Step for Laravel 11 Store JSON Data in Database Example


Step 1: Install Laravel 11

Step 2: Create Migration

Step 3: Create Model

Step 4: Create Route

Step 5: Create Controller

Run Laravel App

Step 1: Install Laravel 11

First of all, we need to get a fresh Laravel 11 version application using the command below because we are starting from scratch. So, open your terminal or command prompt and run the command below:

composer create-project laravel/laravel example-app

Step 2: Create Migration

Here, we need to create a database migration for the "items" table with "title" and "data" (JSON Column) columns, and also we will create a model for the items table.

php artisan make:migration create_items_table

database/migrations/2024_04_11_141714_create_items_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.

*

* @return void

*/

public function up(): void

{

Schema::create('items', function (Blueprint $table) {

$table->id();

$table->string('title');

$table->json('data')->nullable();

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down(): void

{

Schema::dropIfExists('items');

}

};

Then run the migration command to create the items table.

php artisan migrate

Step 3: Create Model

In this step, we will create Item.php model with getter and setter. Let's create the model and update the following code:

php artisan make:model Item

App/Models/Item.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Database\Eloquent\Casts\Attribute;

class Item extends Model

{

use HasFactory;

/**

* Write code on Method

*

* @return response()

*/

protected $fillable = [

'title', 'data'

];

/**

* Get the user's first name.

*

* @return \Illuminate\Database\Eloquent\Casts\Attribute

*/

protected function data(): Attribute

{

return Attribute::make(

get: fn ($value) => json_decode($value, true),

set: fn ($value) => json_encode($value),

);

}

}

Step 4: Create Route

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

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ItemController;

Route::get('item', [ItemController::class, 'index']);

Step 5: Create Controller

In this step, we will create `ItemController` file and write the `index()` method to create item records with an array and access them as an array.

app/Http/Controllers/ItemController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Item;

class ItemController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$input = [

'title' => 'Demo Title',

'data' => [

'1' => 'One',

'2' => 'Two',

'3' => 'Three'

]

];

$item = Item::create($input);

dd($item->data);

}

}

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/item

You can see database output and print variable output:

Database Output:

laravel-11-json-database

Output:

array:3 [

1 => "One"

2 => "Two"

3 => "Three"

]

I hope it can help you...

#Laravel 11