Trong quá trình phát triển ứng dụng Laravel, việc lưu trữ dữ liệu dưới dạng JSON trong cơ sở dữ liệu mang lại nhiều lợi ích, đặc biệt khi bạn cần lưu trữ dữ liệu linh hoạt mà không muốn sử dụng quá nhiều bảng phụ. Laravel 11 cung cấp cách tiếp cận đơn giản và hiệu quả để làm việc với JSON trong cơ sở dữ liệu. Trong bài viết này, codetuthub.com sẽ hướng dẫn bạn cách lưu trữ và truy vấn dữ liệu JSON trong Laravel 11.

1. Cài đặt Laravel 11

Trước tiên, nếu bạn chưa có ứng dụng Laravel 11, hãy cài đặt một dự án mới bằng Composer:

shell
composer create-project --prefer-dist laravel/laravel myapp

Sau đó, di chuyển vào thư mục dự án:

shell
cd myapp

Tiếp theo, chỉnh sửa thông tin kết nối database ở file .env (nhớ thay đổi value phù hợp với máy chủ Database của bạn):

shell
DB_CONNECTION=mysql
DB_HOST=0.0.0.0
DB_PORT=3306
DB_DATABASE=demo_laravel
DB_USERNAME=db_username
DB_PASSWORD=db_password

Chạy migrations và khởi động ứng dụng bằng lệnh:

shell
php artisan migrate
php artisan serve

Ứng dụng của bạn sẽ chạy trên http://127.0.0.1:8000/.

2. Tạo migration với kiểu dữ liệu JSON

Laravel hỗ trợ lưu trữ JSON trực tiếp trong cơ sở dữ liệu MySQL, PostgreSQL và SQLite thông qua kiểu dữ liệu json. Hãy tạo một migration mới để thêm cột JSON vào bảng:

php
php artisan make:migration create_products_table

Sau đó, mở file migration trong thư mục database/migrations/ và chỉnh sửa nội dung như sau:

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.
     */
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->json('details');
            $table->timestamps();
        });
    }

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

Sau khi chỉnh sửa xong, chạy lệnh sau để áp dụng migration:

shell
php artisan migrate

Bây giờ, bảng products đã sẵn sàng để lưu trữ dữ liệu JSON.

3. Tạo model và controller

Tạo model Product để làm việc với dữ liệu:

shell
php artisan make:model Product

Chỉnh sửa file app/Models/Product.php để khai báo cột details là kiểu JSON:

php
app/Models/Product.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'details'];
    protected $casts = [
        'details' => 'array',
    ];
}

Tiếp theo, tạo controller để xử lý lưu trữ và truy vấn dữ liệu JSON:

shell
php artisan make:controller ProductController

Chỉnh sửa file app/Http/Controllers/ProductController.php:

php
app/Http/Controllers/ProductController.php
<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'details' => 'required|array',
        ]);

        $product = Product::create([
            'name' => $request->name,
            'details' => $request->details,
        ]);

        return response()->json(['message' => 'Product saved successfully', 'product' => $product]);
    }

    public function show($id)
    {
        $product = Product::findOrFail($id);
        return response()->json($product);
    }
}

4. Tạo route API trong Laravel 11

Chạy lệnh install:api để cài đặt Laravel Sanctum và tạo các tệp cần thiết để sử dụng api laravel:

shell
php artisan install:api

Mở file routes/api.php và thêm các tuyến API để lưu trữ và lấy dữ liệu JSON:

php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth:sanctum'])->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('/products', [\App\Http\Controllers\ProductController::class, 'store']);
Route::get('/products/{id}', [\App\Http\Controllers\ProductController::class, 'show']);

5. Kiểm tra API với Postman hoặc Curl

Bạn có thể kiểm tra API bằng Postman hoặc Curl.

Tạo một sản phẩm mới:

shell
curl -X POST "http://127.0.0.1:8000/api/products" \
     -H "Content-Type: application/json" \
     -d '{"name": "Laptop Dell", "details": {"CPU": "Intel i7", "RAM": "16GB", "Storage": "512GB SSD"}}'

Đây là dữ liệu được lưu trong database định dạng JSON:

Lấy thông tin sản phẩm:

shell
curl -X GET "http://127.0.0.1:8000/api/products/1"

6. Truy vấn dữ liệu JSON trong Laravel

Laravel cung cấp nhiều cách để truy vấn dữ liệu JSON từ cơ sở dữ liệu.

6.1. Lọc theo giá trị JSON

php
$products = Product::where('details->CPU', 'Intel i7')->get();

6.2. Lấy một giá trị từ JSON

php
$product = Product::find(1);
$cpu = $product->details['CPU'];

6.3. Cập nhật dữ liệu JSON

php
$product = Product::find(1);
$product->details['RAM'] = '32GB';
$product->save();

7. Kết luận

Laravel 11 hỗ trợ lưu trữ và truy vấn dữ liệu JSON một cách linh hoạt, giúp bạn quản lý dữ liệu có cấu trúc động mà không cần tạo nhiều bảng trong cơ sở dữ liệu. Với hướng dẫn này từ codetuthub.com, bạn có thể dễ dàng triển khai lưu trữ JSON trong ứng dụng Laravel của mình.

Source code: https://github.com/vantoantg/laravel-11-demo/tree/json-database

Nếu bạn có bất kỳ câu hỏi nào, hãy để lại bình luận bên dưới!