【问题标题】:Save results from query and store it in JSON file format, then return it - Laravel / Vue保存查询结果并将其存储为 JSON 文件格式,然后返回 - Laravel / Vue
【发布时间】:2019-10-03 23:30:02
【问题描述】:

我正在 Laravel 中制作一个 api 来与前端的 Vue 进行通信。

首先,我不想在每次加载页面时都向数据库发出请求。

解决方法:第一次请求数据库,保存成json文件然后返回,下一次请求只会发送json文件,没有数据库请求。我会在1天后重生。

问题:一切正常,但响应不是有效的 json 格式。所以 Vue 无法获取 json 文件并渲染页面

代码:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Product;
use Storage;

class ProductController extends Controller
{
    public function home () 
    {
        $file = 'json\products.json';
        $fileExists = Storage::disk('local')->exists( $file );
        $storagePath  = Storage::disk('local')->path( $file );

        if ( $fileExists ) {
            if ( time () - 86400 < filemtime ($storagePath ) ) {
                return Storage::get($file);
            }
        }

        $products = Product::select( 'id' , 'name' , 'code' , 'description' , 'size' , 'weight' , 'pic_url' 'pic_video' 'long_description' )->limit(200)->get();

        //Storage::disk('local')->put('json\products.json', json_encode($products, JSON_PRETTY_PRINT) ); //Doesnot Work 
        Storage::disk('local')->put('json\products.json', response()->json(['products' => $products ])); // Doesnot Work

        return response()->json(['products' => $products ] , 200); // This response works , and vue catches and reads perfectly
    }
}

已编辑:返回 Storage::get($file);

Example in browser:

【问题讨论】:

  • 你知道,你可以使用return ['products' =&gt; $products];,它会正确返回 JSON
  • 这样做? Storage::disk('local')->put('json\products.json', ['products' => $products] ); -> 不起作用。
  • 不,我的意思是作为你最后的回报
  • 另外,json\products.json 不是有效的文件夹位置
  • 不,我的意思是作为你的最终回报 -> 这不是这里的问题。问题出在这里:return Storage::get($file);

标签: php json laravel


【解决方案1】:

这样解决:

return cache()->remember($cacheKey, 1440 , function () {
    $products = Product::select( 'id' , 'name' , 'code' , 'description' , 'size' , 'weight' , 'pic_url' 'pic_video' 'long_description' )->limit(200)->get();
    return ['products' => $products];
});

【讨论】:

    猜你喜欢
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多