Category Archive Laravel 11

Byphunsanit

Laravel: manual Asset Cache data with JSON

เพราะว่ามี json ที่ export ทำไว้สำหรับให้ Vue.js หรือ JQuery ดึงข้อมูลไปใช้ เช่น ตัวเลือก options ใน select box ที่ใช้หลายที่ แต่บางครั้งนาน ๆ ทีจะมีการ update ข้อมูลบ้าง เลยเขียน code เอาไว้ update ข้อมูล และใช้ dynamic model ในการช่วยดึงข้อมูล อันนี้จะต่างจากแคชปกติของ laravel เพราะว่าจะเขียนไฟล์ไว้ใน SourceCode/public/assets/options เพราะต้องให้ javascript ทั้ง jQuery, React, Vue.js พวกนี้เข้ามาอ่านข้อมูลได้โดยที่ไม่ query ใหม่ ไม่ต้องใช้ PHP สร้างใหม่ทุกครั้ง หรือต้องมาตรวจดูข้อมูลทุกครั้งที่มีการใช้งาน จึงใช้เฉพาะส่วนที่เป็น public ได้เท่านั้น

  1. สร้าง Controller
    SourceCode/app/Http/Controllers/AssetCacheController.php
    อธิบาย
    บรรทัดที่ 21 เป็นการ load model แบบ dynamic ตามชื่อ model ที่ส่งมา
    บรรทัดที่ 24 เป็น function ที่ดึงข้อมูล option ที่เขียนเพิ่มไว้ใน model
    บรรทัดที่ 61 เป็นส่วนที่เขียนไว้ว่า key ไหน ให้ไปดึงข้อมูลจาก model อะไร
    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    
    class AssetCacheController extends Controller
    {
        /**
         * cacheSelectOptions
         *
         * @param string $key The key to use for the cache file
         * @param string $model The model to get the options from
         * @return write the options to a json file
         *
         * create a json file with the data from the model for the select option
         */
        public function cacheSelectOptions($key, $model)
        {
            // Perform operations with the model
            $modelClass = "App\\Models\\{$model}";
            if (class_exists($modelClass)) {
                if (method_exists($modelClass, 'getOptions')) {
                    $options = (new $modelClass)->getOptions();
    
                    $filePath = public_path('assets/options/' . $key . '.json');
    
                    file_put_contents($filePath, json_encode($options));
                } else {
                    \Log::error('AssetCacheController: Method getOptions() not found in model: ' . $model);
                }
            } else {
                \Log::error('AssetCacheController: Model ' . $model . ' not found');
            }
        }
    
        /**
         * getSelectOptions
         *
         * @param  \Illuminate\Http\Request  $request
         * @return \Illuminate\Http\Response
         *
         * create a json file with the data from the model for the select option and return the data
         */
        public function getSelectOptions(Request $request)
        {
            // Validate the request
            $validator = \Validator::make($request->all(), [
                'key' => 'required|string',
            ]);
    
            if ($validator->fails()) {
                return response()->json(['error' => $validator->errors()], 400);
            }
    
            // Get configuration
            $key = $request->input('key');
    
            switch ($key) {
    
                case 'category_id':
                    $model = 'Category';
                    break;
    
                case 'organization_id':
                    $model = 'Organization';
                    break;
    
                case 'service_line_id':
                    $model = 'ServiceLine';
                    break;
    
                case 'status_id':
                    $model = 'Status';
                    break;
    
                case 'team_id':
                    $model = 'Team';
                    break;
    
                case 'team_support_id':
                    $model = 'TeamUser';
                    break;
    
                case 'vessel_id':
                    $model = 'Vessel';
                    break;
    
                default:
                    \Log::error('AssetCacheController: no assets configuration for ' . $key);
                    return response()->json(['error' => 'Internal server error'], 500);
                    break;
    
            }
    
            $this->cacheSelectOptions($key, $model);
    
            $filePath = public_path('assets/options/' . $key . '.json');
    
            if (file_exists($filePath)) {
                $options = json_decode(file_get_contents($filePath), true);
                return response()->json($options);
            } else {
                return response()->json(['error' => 'Cache file not found'], 404);
            }
        }
    }
    
  2. สร้าง routes API โดยคำสั่ง
    php artisan install:api
  3. เพิ่ม rute
    Route::get('asset/getSelectOptions', [AssetCacheController::class, 'getSelectOptions']);
  4. test โดยลองเรียก url เช่น
    http://127.0.0.1:8000/api/asset/getSelectOptions?key=category_id
    ควรจะมี ไฟล์ SourceCode/public/assets/options/category_id ถูกสร้าง / อัพเดตตามข้อมูลในตาราง ณ ขณะนี้