json_database

How to Store JSON in Database Laravel

Hello Geeks, This tutorial will go over laravel store json in database. This article explains how to store json in a database in Laravel. I’m going to show you how to save json in a database in Laravel. I explained laravel save JSON in db in simple steps.
This example works with Laravel 6, Laravel 7, Laravel 8, and Laravel 9.

When we have large amounts of data or unfixed columns, we cannot create too many nullable fields in a database table. As a result, we must use the JSON data type to store values, allowing us to store large amounts of unstructured data. If you want to store a JSON array in a database in Laravel, I will show you a simple example of how to store and access a JSON array from a database in Laravel.

In this example, we will first create a migration with a JSON column. Then we’ll build a model with a getter and a setter. When creating records, you can pass them as an array, and when retrieving records, you will find an array. So let’s look at a simple example and learn from it.

Step 1: Install Laravel

This is optional; however, if you have not yet created the laravel app, you may proceed with the following command:

composer create-project laravel/laravel example-app

Step 2: Create Migration

We will create a database migration for the “items” table with title and data (JSON Column) columns, as well as a model for the items table.

php artisan make:migration create_products_table

database/migrations/2022_07_11_141714_create_products_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('products', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->json('data')->nullable();
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
};

Then execute the migration command to create the items table.

php artisan migrate

Step 3: Create Model

In this step, we’ll make an Item.php model with a getter and a setter. Let’s make a model and update the following code:

php artisan make:model Product

App/Models/Product.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
  
class Product 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

We will create one route for testing in the third step. Create a single path here.

routes/web.php

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
     
Route::get('product', [ProductController::class, 'index']);

Step 5: Create Controller

In this step, we will create an ItemController file and write the index() method, which will allow us to create item records with an array and access them as an array.

app/Http/Controllers/ProductController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Product;
  
class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $input = [
            'title' => 'Aboutthenerd',
            'data' => [
                '1' => 'One',
                '2' => 'Two',
                '3' => 'Three'
            ]
        ];
  
        $product = Product::create($input);
  
        dd($product->data);
  
    }
}

Run Laravel App:

After you’ve completed all of the necessary steps, type the following command and press enter to launch the Laravel app:

php artisan serve

Now, Enter the following URL into your web browser and view the app output:

http://localhost:8000/product

Leave a Reply