Laravel 11 Store JSON Format Data in Database Tutorial

By Hardik Savani September 14, 2024 Category : Laravel

In this tutorial, I will show you how to store JSON data in database using laravel.

The $casts property in Laravel allows you to specify the data type of certain attributes of your model. When using $casts, Laravel automatically converts attributes between common data types, such as strings, integers, booleans, and JSON.

In this example, we will make a products table with two columns: name and details. The details column will use the JSON data type. Next, we will set up JSON casts for the details column in the Post model. After that, we will create a record and search for a record. Let's go through the steps to understand how it works.

laravel 11 save json data into database

Step for Laravel 11 Store JSON Data in Database Example

  • Step 1: Install Laravel 11
  • Step 2: Create Migration
  • Step 3: Create Model
  • Step 4: Create Route
  • Step 5: Create Controller
  • Run Laravel App:
  • >

Step 1: Install Laravel 11

First of all, we need to get a fresh Laravel 11 version application using the command below because we are starting from scratch. So, open your terminal or command prompt and run the command below:

composer create-project laravel/laravel example-app

Step 2: Create Migration

Here, we need to create a database migration for the "products" table with "name" and "details" (JSON Column) columns, and also we will create a model for the products table.

php artisan make:migration create_products_table

database/migrations/2024_04_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.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->json("details")->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

Then run the migration command to create the items table.

php artisan migrate

Step 3: Create Model

In this step, we will create Product.php model with JSON casts. Let's create the 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;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'details'
    ]; 

    protected $casts = [
        'details' => 'json'    
    ];
}

Step 3: Create Product

n the third step, we will create one route for testing to create new product with json data. So, create one route here.

routes/web.php

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

Now you can see the controller file code:

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 create()
    {
        $input = [
            'name' => 'Gold',
            'details' => [
                'brand' => 'Jewellery', 
                'tags' => ['gold', 'jewellery', 'money']
            ]
        ];

       return Product::create($input);
    }
}

Now, you will see the following output:

{
  "name": "Gold",
  "details": {
    "brand": "Jewellery",
    "tags": [
      "gold",
      "jewellery",
      "money"
    ]
  },
  "updated_at": "2024-09-12T13:12:44.000000Z",
  "created_at": "2024-09-12T13:12:44.000000Z",
  "id": 1
}

Step 3: Search Product

n the third step, we will create one route for testing to search product. So, create one route here.

routes/web.php

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

Now you can see the controller file code:

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 search()
    {
        $product = Product::whereJsonContains('details->tags', 'money')->get();
        return $product;
    }
}

Now, you will see the following output:

[
  {
    "id": 1,
    "name": "Gold",
    "details": {
      "tags": [
        "gold",
        "jewellery",
        "money"
      ],
      "brand": "Jewellery"
    },
    "created_at": "2024-09-12T13:12:44.000000Z",
    "updated_at": "2024-09-12T13:12:44.000000Z"
  }
]

This way you can easily handle json data in laravel.

Output:

I hope it can help you...

Shares