Home Laravel Laravel 9 Store JSON in Database

Laravel 9 Store JSON in Database

by Shahriar Sagor

Hello dev, Today now in this example i will show you laravel 9 store json in database. From here you will learn about laravel 9 store json in database. if you want to know about example of laravel 9 save json in database then i hope you are in a right place. Here you will learn about laravel 9 save json in db.

Sometimes, if we have a large number data or unfixed columns then at this time we can not create too many fields in database table with the nullable field. So on that time we have to use JSON data type to store the values, on that way we can easily store the large data or unstructured data. if we want to store a JSON array in a database in laravel then here I will give you a very simple example of how to store a JSON array store and then access it from the database in laravel 9 appliction.

Now in this example, at first, i will create a migration with a JSON column. Then i will be create a model with a getter and setter. when i create the records then i will pass them as an array and when i will get records then i will find an array. So let’s see the simple example and learn it.

Step 1: Install Laravel

At first of all we have to get the fresh Laravel version application by using the bellow command. So open your terminal OR command prompt and then run the bellow command:

composer create-project laravel/laravel example-app

Step 2: Create Migration

Here, i have to create a database migration for “items” table with title and also data(JSON Column) columns and also i will create model for items table.

php artisan make:migration create_items_table

database/migrations/2022_08_23_748714_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');
    }
};

Then need to run migration command to create the items table.

php artisan migrate
Step 3: Create Model

Now in this step, i will create Item.php model with the getter setter. let’s create the 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

Now in this step i will create one route for the testing. So just 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

Now in this step, i will create the ItemController file and then write index() method to create item records with the 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 needed steps have been done, now we have to type the given in the below command and then hit enter to run the Laravel application:

php artisan serve

Now, just go to your web browser, and then type the given URL and view the application output:

http://localhost:8000/item

Read Also: php artisan serve not working in Laravel

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like