How to Store JSON in Database Laravel 9

Today we are going to learn How to Store JSON in Database Laravel 9. This tutorial will cover on how you can store the JSON value into database in laravel 9.

If the is large data or unfixed columns then you cannot create too many field to save the data to database. Then you have to save the value into JSON in database. This way this load the database smoothly without having load to the database.

Steps on How to Store JSON in Database Laravel 9:

  • Step 1: Installing new fresh Laravel 9 Application
  • Step 2: Creating Database and Migration
  • Step 3: Creating Model
  • Step 4: Creating Route
  • Step 5: Creating Controller
  • Step 6: Testing
  • Step 7: Conclusion

Also Read: Create Ajax CRUD Laravel 9 Application Example

Step 1: Installing new fresh Laravel 9 Application

First, We are going to install a fresh new laravel 9 application. To install a laravel 9 application run the following command in terminal.

composer create-project laravel/laravel save-json-app

cd save-json-app

Note:save-json-app” is the laravel 9 application name.

Step 2: Creating Database and Migration

Now we are going to create a database. Open phpmyadmin and create a new database with name save-json-app.

Enter the database details to .env as shown in below code.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=save-json-app
DB_USERNAME=root
DB_PASSWORD=

Now we are going to create items migration with title and data(as json) columns. To create a migration run the following command in terminal.

php artisan make:migration create_items_table 

Now, Open the items migration file which we can be found inside database/migrations folder and update the following code.

<?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');
    }
};

Now run the migration to create a item table.

php artisan migrate

Also Read: How to Create RSS Feed in Laravel 9 Example

Step 3: Creating Model

Now we are going to create a item model. To create a item model run the following command in terminal.

php artisan make:model Item

Open the item.php file which can be found inside App/Models/ and update the following code.

<?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: Creating Route

Now we are going to create route. enter the following route to 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']);

Also Read: Ajax File Upload with Progress Bar in Laravel 9 Example

Step 5: Creating Controller

Last step is to create a ItemController.php. Create a new file ItemController.php inside app/Http/Controllers and enter the following code to controller.

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

Step 6: Testing

Now, Its time to test our laravel application. First start the laravel server by run the following command.

php artisan serve

and open the following URL in any web browser.

http://127.0.0.1:8000/item

Also Read: Datatables Filter with Dropdown in Laravel 9 Example

You can see database output and print variable output:

Database Output:

How to Store JSON in Database Laravel 9
How to Store JSON in Database Laravel 9

Output:

array:3 [
  1 => "One"
  2 => "Two"
  3 => "Three"
]

Step 7: Conclusion

Today, We had learn How to Store JSON in Database Laravel 9. Hope this tutorial helped you with learning Laravel 9. If you have any question you can ask us at comment section below. If you like the tutorial please subscribe our YouTube Channel and follow us on social network Facebook and Instagram.

Also Read: Create React JS CRUD using Vite in Laravel 9 Example

4 Comments

Leave a Reply