在 Laravel 應用程式中管理多個 CRUD 操作可能會讓人不知所措,尤其是在處理越來越多的模型時。在這篇文章中,我將指導您建立一個通用 CRUD 控制器,它允許您在單一控制器中處理現有和未來的 CRUD 操作。
通用控制器可以幫助:
讓我們一步步深入實作!
先建立一個新控制器:
php artisan make:controller GenericController
以下是如何設計 GenericController 來處理任何模型的 CRUD 操作:
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Str; class GenericController extends Controller { protected function getModel($modelName) { $modelClass = 'App\Models\' . Str::studly($modelName); if (!class_exists($modelClass)) { abort(404, "Model $modelName not found."); } return new $modelClass; } public function index($model) { $modelInstance = $this->getModel($model); return response()->json($modelInstance::all()); } public function show($model, $id) { $modelInstance = $this->getModel($model); return response()->json($modelInstance::findOrFail($id)); } public function store(Request $request, $model) { $modelInstance = $this->getModel($model); $data = $request->validate($modelInstance->getFillable()); $created = $modelInstance::create($data); return response()->json($created, 201); } public function update(Request $request, $model, $id) { $modelInstance = $this->getModel($model); $item = $modelInstance::findOrFail($id); $data = $request->validate($modelInstance->getFillable()); $item->update($data); return response()->json($item); } public function destroy($model, $id) { $modelInstance = $this->getModel($model); $item = $modelInstance::findOrFail($id); $item->delete(); return response()->json(['message' => 'Deleted successfully.']); } }
設定您的路由以使用動態端點:
use App\Http\Controllers\GenericController; Route::controller(GenericController::class)->prefix('api/{model}')->group(function () { Route::get('/', 'index'); Route::get('/{id}', 'show'); Route::post('/', 'store'); Route::put('/{id}', 'update'); Route::delete('/{id}', 'destroy'); });
確保每個模型都有:
Post 模型範例:
namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; protected $fillable = ['title', 'content']; }
這非常適合:
對於更複雜的業務邏輯,您可能仍需要專用的控制器。
以上是如何在 Laravel 中為多種資源建立通用 CRUD 控制器的詳細內容。更多資訊請關注PHP中文網其他相關文章!