Laravel Resource Routes和API Resource Routes讲解

在 Laravel 中,Resource Routes 和 API Resource Routes 是两种用于定义 RESTful 路由的便捷方法。它们帮助开发者快速创建遵循 RESTful 标准的路由集合,分别适用于普通 Web 应用和 API 应用。

Resource Routes

Resource Routes 是为传统的 Web 应用设计的,它们生成了一组常见的 CRUD 路由,同时适用于 Web 中间件组。要定义 Resource Routes,可以使用 Route::resource 方法。下面是一个示例:

use Illuminate\Support\Facades\Route;

Route::resource('posts', 'PostController');

这条命令会生成以下七个路由:

HTTP Method URL Action Route Name
GET /posts index posts.index
GET /posts/create create posts.create
POST /posts store posts.store
GET /posts/ show posts.show
GET /posts/{post}/edit edit posts.edit
PUT/PATCH /posts/ update posts.update
DELETE /posts/ destroy posts.destroy

这些路由适用于处理 Web 请求,因此会加载 web 中间件组,默认情况下包含会话管理、CSRF 保护等功能。

API Resource Routes

API Resource Routes 类似于 Resource Routes,但它们是为 API 设计的,通常不包含会话和 CSRF 保护。使用 Route::apiResource 方法可以定义 API Resource Routes。

use Illuminate\Support\Facades\Route;

Route::apiResource('posts', 'PostController');

这条命令生成的路由与 Route::resource 大致相同,但省略了用于显示和编辑的路由:

HTTP Method URL Action Route Name
GET /posts index posts.index
POST /posts store posts.store
GET /posts/ show posts.show
PUT/PATCH /posts/ update posts.update
DELETE /posts/ destroy posts.destroy

比较与选择

  • Resource Routes

    • 包含所有七个 RESTful 动作:index、create、store、show、edit、update、destroy。
    • 适用于传统 Web 应用,需要会话、CSRF 保护等功能。
    • 使用 Route::resource 方法定义。
  • API Resource Routes

    • 省略 create 和 edit 路由,仅包含 index、store、show、update、destroy。
    • 适用于 API 应用,不需要会话和 CSRF 保护。
    • 使用 Route::apiResource 方法定义。

示例:定义和使用

Resource Routes 示例

控制器方法示例:

class PostController extends Controller
{
    public function index()
    {
        // 显示所有资源
    }

    public function create()
    {
        // 显示创建资源的表单
    }

    public function store(Request $request)
    {
        // 存储新资源
    }

    public function show($id)
    {
        // 显示单个资源
    }

    public function edit($id)
    {
        // 显示编辑资源的表单
    }

    public function update(Request $request, $id)
    {
        // 更新资源
    }

    public function destroy($id)
    {
        // 删除资源
    }
}

API Resource Routes 示例

控制器方法示例:

class PostController extends Controller
{
    public function index()
    {
        // 返回所有资源
    }

    public function store(Request $request)
    {
        // 存储新资源
    }

    public function show($id)
    {
        // 返回单个资源
    }

    public function update(Request $request, $id)
    {
        // 更新资源
    }

    public function destroy($id)
    {
        // 删除资源
    }
}

选择哪种路由定义方法取决于你的应用需求。如果你开发的是一个需要视图和表单的传统 Web 应用,使用 Resource Routes。如果你开发的是 RESTful API 服务,使用 API Resource Routes 更为合适。

posted @ 2024-05-15 15:18  Laravel自学开发  阅读(153)  评论(0编辑  收藏  举报