在 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中文网其他相关文章!