How to Store JSON Data in Database in Laravel (with example)

https://laracoding.com/wp-content/uploads/2023/06/how-to-store-json-data-in-database-in-laravel-with-example_841.png

Storing JSON data in a Laravel database provides a flexible solution for managing dynamic attributes or unstructured data. In this tutorial, we will walk through the process of storing JSON data in a Laravel database, using a practical example of storing product attributes. By the end of this tutorial, you will have a clear understanding of how to store and retrieve JSON data efficiently using Laravel.

Step 1: Setting up a Laravel Project

Create a new Laravel project using the following command:

laravel new json-data-storage

Step 2: Creating the Products Table Migration

Generate a migration file to create the products table using the command:

php artisan make:migration create_products_table --create=products

Inside the generated migration file (database/migrations/YYYY_MM_DD_create_products_table.php), define the table schema with a JSON column for the attributes:

<?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->json('attributes');
            $table->timestamps();
        });
    }

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

Step 3: Running the Migration

Run the migration using the following command:

php artisan migrate

Step 4: Creating the Product Model

Generate a Product model using the command:

php artisan make:model Product

In the Product model (app/Models/Product.php), add the $casts property to specify that the attributes attribute should be treated as JSON:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $casts = [
        'attributes' => 'json',
    ];
}

Step 5: Storing Product Attributes as JSON

To store product attributes as JSON, we can simply use Laravel’s Eloquent model. Create a new Product instance, set the desired attributes as an array, and save it:

use App\Models\Product;

$product = new Product;
$product->attributes = [
    'color' => 'red',
    'size' => 'medium',
    'weight' => 0.5,
];
$product->save();

Step 6: Retrieving JSON Data

To retrieve the attributes of a product, you can access the attributes property on the model:

$product = Product::find(1);
$attributes = $product->attributes;

If you want to access a specific attribute within the JSON data, you can do so by using array access:

$color = $product->attributes['color'];

By accessing the attributes property, you can retrieve the JSON data associated with the product and access specific attributes as needed.

Step 7: Manipulating JSON Data (Full Array)

To update all the attributes of the product at once, you can assign a new array with all the key-value pairs and use Eloquent’s save() method to update the record directly.

$product = \App\Models\Product::find(1);
$product->attributes = [
    'color' => 'green',
    'size' => 'large',
    'weight' => 2.5,
];
$product->save();

Step 8: Manipulating JSON Data (One Value)

Updating a single value within the JSON data requires a slightly different approach in Laravel and has one important caveat. Directly modifying the attribute like $product->attributes['weight'] = 1.0 and saving the product will result in an ErrorException: “Indirect modification of overloaded property App\Models\Product::$attributes has no effect.”

To overcome this issue, you can follow the solution below:

$product = \App\Models\Product::find(1);
$attributes = $product->attributes; // create a copy of the array
$attributes['weight'] = 0.6; // modify the value in the copied array
$product->attributes = $attributes; // assign the copied array back to $product->attributes
$product->save();

Conclusion

Storing JSON data in a database using Laravel provides flexibility and convenience when working with dynamic or unstructured data. By following the steps outlined in this tutorial, you have learned how to create the necessary migrations and models, store and retrieve JSON data, and manipulate the JSON data efficiently. This knowledge equips you with the tools to handle various use cases in your Laravel applications and opens up possibilities for efficiently managing complex data structures.

Start implementing JSON data storage in your Laravel projects and unlock the full potential of your application’s data management capabilities. Happy coding!

Laravel News Links