Laravel资源控制器通过Route::resource定义RESTful路由,自动生成七种CRUD操作方法,支持only/except筛选,可自定义URI、注入服务、使用中间件及返回JSON响应。

Laravel资源控制器,简单来说,就是为了更方便地处理CRUD(创建、读取、更新、删除)操作而生的。它遵循RESTful架构,让你的代码更简洁、易维护。
php artisan make:controller PhotoController --resource
资源路由让你可以用一行代码定义多个路由,对应资源控制器的不同方法。比如:
Route::resource('photos', PhotoController::class);这行代码会生成七个路由:
index
create
store
show
edit
update
destroy
only
except
Route::resource('photos', PhotoController::class)->only(['index', 'show']);
Route::resource('photos', PhotoController::class)->except(['create', 'store', 'destroy']);资源控制器自带了一些预定义的方法,每个方法都对应一个特定的HTTP请求和操作。
index()
create()
store()
show($id)
edit($id)
update(Request $request, $id)
destroy($id)
这些方法都是为了遵循RESTful架构而设计的,每个方法都对应一个特定的HTTP方法和URI。
有时候,你可能想要自定义资源控制器的URI,比如把
/photos
/images
Route::resource('images', PhotoController::class, ['names' => 'photos']);这个
names
route()
return redirect()->route('photos.index'); // 生成 /images另外,如果你想完全自定义URI,可以手动定义每一个路由,而不是使用
Route::resource()
在
store()
update()
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|max:255',
'description' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
// 创建并保存资源
}$request->validate()
$validatedData
在API开发中,通常需要返回JSON响应。Laravel提供了方便的方法来生成JSON响应:
public function index()
{
$photos = Photo::all();
return response()->json($photos);
}response()->json()
return response()->json($photos, 200); // 200 OK return response()->json(['error' => 'Not found'], 404); // 404 Not Found
Laravel的依赖注入容器可以帮助你解耦代码,提高可测试性。你可以在资源控制器的构造函数中注入依赖:
protected $photoService;
public function __construct(PhotoService $photoService)
{
$this->photoService = $photoService;
}
public function index()
{
$photos = $this->photoService->getAllPhotos();
return view('photos.index', compact('photos'));
}这样,你就可以在控制器中使用
$this->photoService
PhotoService
你可以在资源控制器中使用中间件来处理请求。比如,你可以使用
auth
public function __construct()
{
$this->middleware('auth')->except(['index', 'show']);
}这个例子中,除了
index
show
以上就是Laravel资源控制器?RESTful控制器如何使用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号