資源路由(CURD)



資源路由

#資源路由, 可快速產生一批路由, 特別適合CURD操作

支援設定RESTFul要求的資源路由,方法如下:

Route::resource('blog', 'Blog');

表示註冊了一個名稱為blog的資源路由到Blog控制器,系統會自動註冊7個路由規則,如下:


## savePOSTsave##readblog/:id#edit blog/:id/editupdateblog/:iddeleteblog/:id
標識請求類型#產生路由規則對應操作方法(預設)
indexGET#blogindex
#createGETblog/createcreate
blog
GETread
GETedit
PUTupdate
#DELETEdelete


具體指向的控制器由路由位址決定,你只需要為Blog控制器建立以上對應的操作方法就可以支援下面的URL存取:

http://serverName/blog/
http://serverName/blog/128
http://serverName/blog/28/edit

Blog控制器中的對應方法如下:

<?php
namespace app\controller;

class Blog
{
    public function index()
    {
    }

    public function read($id)
    {
    }

    public function edit($id)
    {
    }
}

可以透過命令列快速建立一個資源控制器類別(參考後面的控制器章節的資源控制器一節)。

可以改變預設的id參數名,例如:

Route::resource('blog', 'Blog')
    ->vars(['blog' => 'blog_id']);

控制器的方法定義需要調整如下:

<?php
namespace app\controller;

class Blog
{
    public function index()
    {
    }

    public function read($blog_id)
    {
    }

    public function edit($blog_id)
    {
    }
}

也可以在定義資源路由的時候限定執行的方法(標識),例如:

// 只允许index read edit update 四个操作
Route::resource('blog', 'Blog')
    ->only(['index', 'read', 'edit', 'update']);
    
// 排除index和delete操作
Route::resource('blog', 'Blog')
    ->except(['index', 'delete']);

資源路由的標識不可更改,但產生的路由規則和對應操作方法可以修改。

如果需要更改某個資源路由標識的對應操作,可以使用下面方法:

Route::rest('create',['GET', '/add','add']);

設定之後,URL存取變成:

http://serverName/blog/create
变成
http://serverName/blog/add

建立blog頁面的對應的操作方法也變成了add。

支援批次更改,如下:

Route::rest([
    'save'   => ['POST', '', 'store'],
    'update' => ['PUT', '/:id', 'save'],
    'delete' => ['DELETE', '/:id', 'destory'],
]);

資源巢狀


支援資源路由的巢狀,例如:

Route::resource('blog', 'Blog');
Route::resource('blog.comment','Comment');

就可以存取以下位址:

http://serverName/blog/128/comment/32
http://serverName/blog/128/comment/32/edit

產生的路由規則分別是:

blog/:blog_id/comment/:id
blog/:blog_id/comment/:id/edit

Comment控制器對應的操作方法如下:

<?php

namespace app\controller;

class Comment
{
    public function edit($id, $blog_id)
    {
    }
}

edit方法中的參數順序可以隨意,但參數名稱必須滿足定義要求。

如果需要改變其中的變數名,可以使用:

// 更改嵌套资源路由的blog资源的资源变量名为blogId
Route::resource('blog.comment', 'index/comment')
    ->vars(['blog' => 'blogId']);

Comment控制器對應的操作方法改為:

<?php
namespace app\controller;

class Comment
{
    public function edit($id, $blogId)
    {
    }
}