Store JSON in Database using LARAVEL 10

Spread the love

Hello Guys,

Let’s delve into an Store JSON in Database example in Laravel 9, demonstrating how to efficiently “Store JSON in Database.” Discover the seamless process of saving JSON data within your Laravel 9 database. If you’re seeking a practical illustration of saving JSON data in a Laravel 9 database, you’re in the right place. Master the art of “Laravel 9 save JSON in a database.”

In scenarios where extensive data or variable columns hinder the addition of numerous nullable fields to a database table, utilizing the JSON data type becomes imperative. Allow me to provide a simplified guide on storing a JSON array in a Laravel database and accessing it effortlessly.

Our journey begins with the creation of a migration featuring a JSON column. Subsequently, we’ll fashion a model replete with getter and setter methods. As you generate records, you can input them as an array, and upon retrieval, you’ll find them neatly organized as an array. Embark on this enlightening journey by exploring our straightforward example.

Example of Store JSON in Database:

Step 1: Install Laravel

While it’s not mandatory, you have the option to execute the following command in case you haven’t already established your Laravel application:

Also Read: How to Create Custom Helper Functions in LARAVEL 10

composer create-project laravel/laravel example-app

Step 2: Create Migration

In this step, we’ll guide you through the process of setting up a database migration specifically tailored for the “items” table. This table contains essential columns for both the title and data (in JSON format), along with a dedicated model designed specifically for managing items within the table.

php artisan make:migration create_items_table

database/migrations/2023_02_01_141152_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()
    {
        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()
    {
        Schema::dropIfExists('items');
    }
};

After completing the necessary steps, be sure to execute the migration command to create the items table.

Also Read: How to Add Foreign Key in MIGRATION using Laravel?

php artisan migrate

Step 3: Create Model

In this stage, we will construct the Item.php model, incorporating both getter and setter methods. Let’s commence by creating the model and implementing the code adjustments provided:

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 stage, we will create a single testing route. Therefore, let’s focus on designing just one route for this purpose.

Also Read: How to Rollback Migration in Laravel?

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’ll create the ItemController file and implement the index() method, enabling you to efficiently build item records using an array and access them seamlessly 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:

Once you’ve completed all the essential steps, it’s time to execute the following command and hit Enter to initiate the Laravel application:

Launch the Laravel application by executing the provided command after completing all the required steps and pressing Enter.

Also Read: how to Create Custom Artisan Command in LARAVEL

php artisan serve

To access the application’s output, simply input the provided URL into your web browser.

http://localhost:8000/item

Uncover the ultimate insights in our collection, your gateway to the best Laravel blog content.

Leave a Comment