How to Store JSON in Database Using Laravel 10?

10-Apr-2023

.

Admin

How to Store JSON in Database Using Laravel 10?

Hi dev,

Some of the most important Laravel 10 store json in database examples are provided in this post. I was clear in my explanation of how Laravel 10 stores JSON. You can comprehend how Laravel 10 saves JSON to the database. We will put into practise a Laravel 10 store JSON in DB in this tutorial.

JSON (also known as JavaScript Object Notation) is a simple, text-based data transmission format that is simple for both humans and machines to parse and generate. JSON is a well-liked data format that is used for data interchange between systems, APIs, and online applications. Key-value pairs are used to represent JSON data, and the syntax is akin to JavaScript object literals. A comma and curly brackets are used to divide and enclose each key-value pair. Values can be strings, numbers, boolean values, arrays, or nested JSON objects; keys are always strings.

In some cases, having vast amounts of data or unfixed columns prevents us from adding too many nullable fields to a database table. So, in order to store values that are huge or unstructured, we must utilise the JSON data type. I'll give you a straightforward example of how to store a JSON array and access it from the database in Laravel if you want to store a JSON array in a database.

As a first step in this example, a migration containing a JSON column will be created. Next, a model with getter and setter methods will be developed. Data can be passed as an array when creating records, and an array is returned when retrieving records. So let's look at a straightforward example to see how to put this into practise.

Step 1: Install Laravel


This is optional; 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: Create Migration

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

php artisan make:migration create_items_table

database/migrations/2022_07_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 migration command to create items table.

php artisan migrate

Step 3: Create Model

In this step, we will create Item.php model with getter setter. let's create model and update 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 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;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

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

Step 5: Create Controller

In this step, we will create ItemController file and write index() method to create item records with array and access as 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:

Output:

array:3 [

1 => "One"

2 => "Two"

3 => "Three"

]

I hope it can help you...

#Laravel 10