In this post, I will show you how to save JSON format data into database in laravel 11 application.
JSON (JavaScript Object Notation) is a lightweight, text-based format for data exchange that is easy for humans to read and write and easy for machines to parse and generate. JSON is a popular data format used in web applications, APIs, and data exchange between systems. JSON data is represented as key-value pairs and uses a syntax similar to JavaScript object literals. Each key-value pair is separated by a comma and enclosed in curly braces {}. Keys are always strings, while values can be strings, numbers, boolean values, arrays, or nested JSON objects.
Sometimes, if we have large data or unfixed columns, then we cannot create too many fields in a database table with the nullable field. So we have to use JSON data type to store values; that way, we can store large data or unstructured data. If you want to store a JSON array in a database in Laravel, then I will give you a simple example of how to store a JSON array, store, and access it from the database in Laravel.
In this example, we will start by creating a migration with a JSON column. Then we will create a model with getter and setter methods. When creating records, we can pass data as an array, and when retrieving records, we will receive an array. So let's take a look at a simple example to learn how to implement this.
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 "items" table with "title" and "data" (JSON Column) columns, and also we will create a model for the items table.
php artisan make:migration create_items_table
database/migrations/2024_04_11_141714_create_items_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(): void {
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->json('data')->nullable();
$table->timestamps(); });
}
/**
Reverse the migrations.
* @return void
*/
public function down(): void
{
Schema::dropIfExists('items');
}
};
Then run the migration command to create the items table.
php artisan migrate
Step 3: Create Model
In this step, we will create Item.php model with getter and setter. Let's create the model and update the following code:
php artisan make:model Item
App/Models/Item.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
class Item extends Model
{
use HasFactory;
end this convetsation....