리소스 라우팅(CURD)



리소스 라우팅

특히 CURD 작업에 적합한 경로 배치를 빠르게 생성할 수 있는 리소스 라우팅

다음과 같이 RESTFul 요청에 대한 리소스 라우팅 설정을 지원합니다.

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

는 다음과 같은 이름의 블로그를 등록하는 것을 의미합니다. 리소스가 블로그 컨트롤러로 라우팅되면 시스템은 자동으로 다음과 같은 7개의 라우팅 규칙을 등록합니다.


indexcreate
Identification요청 유형라우팅 규칙 생성해당 작업 방법(기본값)
indexGET블로그blogindex
createGETblog/createcreate
savePOSTblogsave
readGETblog/:idread
editGETblog/:id/editedit
updatePUTblog/:idupdate
deleteDELETEblog/:id

GET

블로그/생성

create

save

POST

블로그

save

read

GET

blog/:id

read


edit

GET

blog/ :id/edit

edit

update

PUT

blog/ :id

update

delete🎜🎜DELETE🎜🎜blog/ :id🎜🎜delete🎜🎜🎜🎜🎜🎜🎜🎜지정되는 특정 컨트롤러는 라우팅 주소에 따라 결정됩니다. Blog 컨트롤러가 다음을 지원하려면 위의 해당 작업 방법만 생성하면 됩니다. URL 액세스: 🎜
http://serverName/blog/
http://serverName/blog/128
http://serverName/blog/28/edit
🎜블로그 컨트롤러의 해당 메소드는 다음과 같습니다. 🎜
<?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)
    {
    }
}
🎜예를 들어 리소스 라우팅을 정의할 때 실행 메서드(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
🎜블로그 페이지 생성에 해당하는 작업 방법도 추가됩니다. 🎜🎜다음과 같이 일괄 변경을 지원합니다. 🎜
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)
    {
    }
}
🎜편집 방법에서 매개변수의 순서는 임의적일 수 있지만 매개변수 이름은 정의 요구 사항을 충족해야 합니다. 🎜🎜변수 이름을 변경해야 하는 경우 다음을 사용할 수 있습니다. 🎜
// 更改嵌套资源路由的blog资源的资源变量名为blogId
Route::resource('blog.comment', 'index/comment')
    ->vars(['blog' => 'blogId']);
🎜Comment 컨트롤러의 해당 작업 방법이 다음으로 변경됩니다. 🎜
<?php
namespace app\controller;

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