How To Save and Search JSON Data in Laravel 11 Database

Reading Time: 4 minutes
75 Views

In this blog, you’ll learn how to efficiently store and search JSON data within a Laravel 11 database. We’ll cover how to create a database structure that supports JSON fields, store JSON data in those fields, and use Laravel’s powerful query builder to perform searches on the JSON data.

This guide will help you manage and query structured data with ease, taking full advantage of Laravel’s native support for JSON columns.

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

Setup Model and Migration

Open project into terminal and run this command,

php artisan make:model Product -m

It will create two files: xxx_025829_create_products_table.php inside database/migrations folder and Product.php inside app/Models folder.

Open Migration file and write this complete code into it,

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

Open Model class file and write this complete code into it,

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

Run Migration

Next, you need to migrate migration files,

php artisan migrate

This command will create tables inside database.

Product Controller Settings

Run this command to create a product controller class,

php artisan make:controller ProductController

It will create a file named ProductController.php inside /app/Http/Controllers folder.

Open file and write this complete code into it,

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;

class ProductController extends Controller
{
    // Save Product to Database
    public function create()
    {
        $input = [
            'name' => 'Gold',
            'details' => [
                'brand' => 'Jewellery', 
                'tags' => ['gold', 'jewellery', 'money']
            ]
        ];

       return Product::create($input);
    }

    // Search Product from Database
    public function search()
    {
        $product = Product::whereJsonContains('details->tags', 'money')->get();
        return $product;
    }
}

Add Route

Open routes/web.php and add this route into it,

//...
use App\Http\Controllers\ProductController;

Route::get('product/create', [ProductController::class, 'create']);
Route::get('product/search', [ProductController::class, 'search']);

Application Testing

Run this command into project terminal to start development server,

php artisan serve

To Create Product,

URL: http://127.0.0.1:8000/product/create

Output

{
    "name": "Gold",
    "details": {
      "brand": "Jewellery",
      "tags": [
      "gold",
      "jewellery",
      "money"
     ]
    },
    "updated_at": "XXXXXXX",
    "created_at": "XXXXXXX",
    "id": 1
}

To Search Product,

URL: http://127.0.0.1:8000/product/search

Output,

[
    {
        "id": 1,
        "name": "Gold",
        "details": {
            "brand": "Jewellery",
            "tags": [
                "gold",
                "jewellery",
                "money"
            ]
        },
        "created_at": "XXXXX",
        "updated_at": "XXXXX"
    }
]

That’s it.

We hope this article helped you to learn about How To Save and Search JSON Data in Laravel 11 Database in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.