You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel应用中如何读写JSON文件?无需使用MySQL数据库

Laravel 使用JSON文件存储/读取数据(无需数据库)

一、文件存放位置

推荐把JSON文件放在Laravel的storage/app目录下,比如创建storage/app/json_data文件夹专门存放这类文件,或者直接用storage/app/data.json。这个目录有合适的读写权限,且属于Laravel的应用存储区,默认不会被Git误提交。

二、核心工具:Laravel Filesystem门面

Laravel自带的Storage封装了文件操作,比原生PHP文件函数更安全、便捷,直接用它来处理JSON文件即可。

三、具体实现代码

1. 读取JSON数据

use Illuminate\Support\Facades\Storage;

// 读取JSON文件内容
$jsonContent = Storage::get('data.json');
// 转成PHP数组(第二个参数true转数组,false转对象)
$data = json_decode($jsonContent, true);

// 文件不存在或解析失败时返回空数组
if (!$data) {
    $data = [];
}

2. 写入JSON数据

use Illuminate\Support\Facades\Storage;

// 要存储的单条数据
$newData = [
    'id' => 1,
    'name' => 'Test Item',
    'created_at' => now()->toDateTimeString()
];

// 读取现有数据(如需追加数据)
$existingData = json_decode(Storage::get('data.json'), true) ?? [];
$existingData[] = $newData;

// 转成格式化的JSON字符串(支持中文不转义)
$jsonContent = json_encode($existingData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

// 写入文件
Storage::put('data.json', $jsonContent);

四、代码存放位置

  • 快速测试/简单场景:直接写在控制器方法里,比如处理前端请求的控制器:
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Storage;

class JsonDataController extends Controller
{
    // 读取数据接口
    public function index()
    {
        $data = json_decode(Storage::get('data.json'), true) ?? [];
        return response()->json($data);
    }

    // 存储数据接口
    public function store()
    {
        $input = request()->validate([
            'name' => 'required|string'
        ]);

        $existingData = json_decode(Storage::get('data.json'), true) ?? [];
        $existingData[] = array_merge($input, [
            'id' => count($existingData) + 1,
            'created_at' => now()->toDateTimeString()
        ]);

        Storage::put('data.json', json_encode($existingData, JSON_PRETTY_PRINT));

        return response()->json(['message' => '数据存储成功']);
    }
}
  • 复杂/复用场景:创建自定义服务类封装逻辑,比如app/Services/JsonStorageService.php:
namespace App\Services;

use Illuminate\Support\Facades\Storage;

class JsonStorageService
{
    protected $filePath;

    public function __construct($filePath = 'data.json')
    {
        $this->filePath = $filePath;
    }

    // 读取数据
    public function read()
    {
        if (!Storage::exists($this->filePath)) {
            return [];
        }
        $content = Storage::get($this->filePath);
        return json_decode($content, true) ?? [];
    }

    // 覆盖写入数据
    public function write(array $data)
    {
        $jsonContent = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        return Storage::put($this->filePath, $jsonContent);
    }

    // 追加数据
    public function append(array $newItem)
    {
        $existingData = $this->read();
        $existingData[] = $newItem;
        return $this->write($existingData);
    }
}

然后在控制器中注入使用:

namespace App\Http\Controllers;

use App\Services\JsonStorageService;

class JsonDataController extends Controller
{
    protected $storageService;

    public function __construct(JsonStorageService $storageService)
    {
        $this->storageService = $storageService;
    }

    public function index()
    {
        $data = $this->storageService->read();
        return response()->json($data);
    }

    public function store()
    {
        $input = request()->validate([
            'name' => 'required|string'
        ]);
        $this->storageService->append(array_merge($input, [
            'id' => count($this->storageService->read()) + 1,
            'created_at' => now()->toDateTimeString()
        ]));
        return response()->json(['message' => '数据追加成功']);
    }
}

五、注意事项

  • 权限问题:部署时确保storage目录有正确的读写权限,可执行chmod -R 755 storage调整。
  • 并发写入:高并发场景下JSON文件可能出现写入冲突,建议加文件锁或改用数据库。
  • 数据结构:提前规划好JSON结构,避免后期数据混乱。

内容的提问来源于stack exchange,提问作者Alberto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:20:42