Laravel : How to store json format data in database?

Laravel : How to store json format data in database?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Storing JSON Data in MySQL: A Laravel Approach

Handling structured data that doesn't fit neatly into rigid relational columns is a common challenge in modern web development. You might encounter scenarios where you need to store hierarchical information, like a country and its list of divisions, within a single record. The source material presents a specific case: storing an array of division names for a region identified by an ID like "bangladesh".

The core question is how to persist this JSON payload using a Laravel controller while ensuring the data remains accessible and queryable in MySQL.

Understanding the Data Structure

Before writing code, it is essential to understand what you are trying to store. The input JSON looks like this:

{
    "id": "bangladesh",
    "divisions": [
        {"name": "Barisal"},
        {"name": "Chittagong"},
        {"name": "Dhaka"},
        {"name": "Khulna"},
        {"name": "Rajshahi"},
        {"name": "Rangpur"},
        {"name": "Sylhet"}
    ]
}

In a relational database, you could argue for normalizing this into two tables: one for countries and one for divisions with a foreign key relationship. However, if the requirement is to store the list of divisions as an attribute of the country record itself (perhaps for caching purposes or to avoid N+1 queries in specific views), MySQL supports storing JSON natively since version 5.7.

Preparing the Database Schema

You cannot simply dump a string into a standard VARCHAR column if you want to leverage MySQL's JSON capabilities. You must define the column type explicitly. In your migration file, update the schema for the divisions column:

Schema::create('countries', function (Blueprint $table) {
    $table->id();
    $table->string('name'); // e.g., "Bangladesh"
    $table->json('divisions')->nullable(); 
    // Alternatively, you can store the raw JSON string if version constraints allow
});

If you are on a very old version of MySQL (pre-5.7), you would need to store this as a TEXT column and handle parsing entirely in your application logic using functions like FROM_JSON. Assuming you have access to MySQL 5.7 or later, the JSON type is preferred because it offers built-in indexing and extraction capabilities.

Implementing the Controller Logic

The original snippet in the source material contains several syntax errors, such as mixing $user with $div without definition and attempting to pass a raw array directly into json_encode without proper structure. Here is how you should correctly construct the JSON object from an incoming request or a local array.

Laravel provides helpers like old() and request() to access input, but for this specific use case, we assume the data structure is prepared in memory.

public function saveUser(Request $request)
{
    // Define the region and its divisions
    $regionData = [
        'id' => 'bangladesh',
        'divisions' => [
            ['name' => 'Barisal'],
            ['name' => 'Chittagong'],
            ['name' => 'Dhaka'],
            ['name' => 'Khulna'],
            ['name' => 'Rajshahi'],
            ['name' => 'Rangpur'],
            ['name' => 'Sylhet']
        ]
    ];

    // Create the model instance
    $div = new Div();

    // Convert the array to a JSON string
    // Using json_encode with JSON_UNESCAPED_SLASHES and JSON_PRETTY_PRINT 
    // makes debugging easier, but for storage, default is usually fine.
    $div->json_data = json_encode($regionData);

    // Save the record
    $div->save();

    return redirect('getList');
}

Accessing and Querying the Data

Storing the data is only half the battle; retrieving it efficiently is where JSON in MySQL shines. If you stored your divisions as a simple string, you would have to use LIKE '%Dhaka%' queries, which are slow and error-prone.

With a proper JSON column, you can extract specific fields using the dot notation or the ->> operator:

SELECT 
    id, 
    name, 
    json_extract(divisions, '$[0].name') as first_division 
FROM countries 
WHERE json_type(divisions) = 'ARRAY';

In your Laravel controller, you can access this data directly without needing to json_decode manually every time if you cast the attribute appropriately, though MySQL returns it as a string by default unless you use Eloquent's JSON column casting features available in newer versions.

Trade-offs and Considerations

While storing JSON is convenient, it introduces specific trade-offs. You lose the referential integrity that foreign keys provide. If you need to enforce rules like "every division must exist in a master divisions table," a relational approach is safer.

However, if your goal is to store a snapshot of data that changes infrequently or serves as a denormalized view for reporting, JSON offers significant flexibility. It allows you to evolve the schema without running complex migrations. Just remember that indexing works differently on JSON columns; you can create generated columns based on JSON paths to index specific values, but you cannot index every key-value pair within the document automatically.

For more detailed guidance on handling complex data structures and migrations in Laravel, resources like https://laravelcompany.com often provide community-driven insights into schema design patterns.

Our network