In Laravel 11, define the cast attribute on the Model class, which allows users to store and retrieve structured data in JSON format from database.
Let’s start to implement save, retrieve and update json data in database using casts attribute:
Step 1: Create Model and Migration
Run the following Artisan commands to create a model and migration:
php artisan make:model JsonData -m
Step 2: Define Schema in Migration
Open the migration file located in the database/migrations
folder and define the schema for your table. For example:
Schema::create('json_data', function (Blueprint $table) {
$table->id();
$table->json('data');
$table->timestamps();
});
Run migration to create tables:
php artisan migrate
Step 3: Define Casts in Model
Open the JsonData
model (app/Models/JsonData.php
by default) and define the casts
property to specify which attributes should be cast to JSON:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class JsonData extends Model
{
use HasFactory;
protected $fillable = ['data'];
protected $casts = [
'data' => 'array',
];
}
Step 4: Store and Retrieve JSON Data
Now you can easily store and retrieve JSON data using Eloquent without worrying about encoding or decoding:
use App\Models\JsonData;
$jsonData = ['name' => 'John Doe', 'email' => '[email protected]'];
$jsonModel = new JsonData();
$jsonModel->data = $jsonData;
$jsonModel->save();
// Retrieve JSON data
$jsonModel = JsonData::find(1);
$jsonData = $jsonModel->data;
// Manipulate JSON data
$jsonModel->data['name'] = 'Jane Doe';
$jsonModel->save();
With just four steps guide you can store, update, and retrieve json data from database.