Laravel 10 Store JSON in Database Example

JSON is a flexible data format that allows you to store complex and nested data structures. By storing JSON in the database, you can easily handle varying data structures without the need to define a fixed database schema. This can be especially useful when dealing with dynamic or rapidly changing data.

Step 1: Install Laravel

composer create-project laravel/laravel example-app

Step 2: Create Migration

 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

php artisan migrate

Step 3: Create Model

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

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

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);

        }
    }

Run Laravel App:

php artisan serve

Now, Go to web browser, type the URL and view the app output:

http://localhost:8000/item