首页 Order Laravel 正文

Laravel 资源嵌套.浅嵌套.自定义

金鹏头像 金鹏 Laravel 2022-04-01 11:04:26 0 404
导读:一.嵌套资源1. 在一篇博文(Blog)下有多条评论(Comment),编辑某条博文下的一条评论;2.  以上需求,可以通过嵌套资源路由来实现这个功能...
嵌套资源

1. 在一篇博文(Blog)下有多条评论(Comment),编辑某条博文下的一条评论;

2.  以上需求,可以通过嵌套资源路由来实现这个功能;

php artisan make:controller CommentController --resource

//嵌套资源路由

Route ::resource( 'blogs.comments ', 'CommentController ');

 

 

HTTP 类型

路由 URI

制器方法

由命名

GET

blogs/{blog}/comments

index()

blogs.comments.index

GET

blogs/{blog}/comments/create

create()

blogs.comments.create

POST

blogs/{blog}/comments

store()

blogs.comments.store

GET

blogs/{blog}/comments/{comment}

show()

blogs.comments.show

GET

blogs/{blog}/comments/{comment}/edit

edit()

blogs.comments.edit

PUT/PATCH

blogs/{blog}/comments/{comment}

update()

blogs.comments.update

DELETE

blogs/{blog}/comments/{comment}

destroy()

blogs.comments.destroy

 

3.  上需求,可以通过嵌套资源路由来实现这个功能,编辑方法以及传参如下:

public function edit($blog_id, $comment_id)

{

return '编辑博文下的评论,博文 id  '.$blog_id. ',评论 id  '.$comment_id;

}

4. 而实际上,每个 id 都是独立唯一的,并不需要父 id和子 id 同时存在;

5. 为了优化资源嵌套,通过路由方法->shallow()实现浅层嵌套方法

//浅层嵌套

Route ::resource( 'blogs.comments ', 'CommentController ')->shallow();


6. 实现后的路由,在传递参数方法也比较精准,具体如下:

 

 

HTTP 类型

路由 URI

制器方法

由命名

GET

blogs/{blog}/comments

index()

blogs.comments.index

GET

blogs/{blog}/comments/create

create()

blogs.comments.create

POST

blogs/{blog}/comments

store()

blogs.comments.store

GET

comments/{comment}

show()

blogs.comments.show

GET

comments/{comment}/edit

edit()

blogs.comments.edit

PUT/PATCH

comments/{comment}

update()

blogs.comments.update

DELETE

comments/{comment}

destroy()

blogs.comments.destroy

 

public function edit($id)

{

return '评论 id. '.$id;

}

 

7. 如果觉得资源路由命名过长,可以自己自定义,有两种方式:

->name( 'index ', 'b.c.i ');

->names([

'index ' =>  'b.c.i '

]);

 

8. 如果觉得资源路由的参数不符合你的心意,也可以改变:

->parameter( 'blogs ', 'id ');

->parameters([

'blogs '    =>  'blog_id ',

'comments '  =>  'comment_id '

]);


本文地址:https://www.jinpeng.work/?id=153
若非特殊说明,文章均属本站原创,转载请注明原链接。
广告3

欢迎 发表评论:

  • 请填写验证码

日历

«    2025年4月    »
123456
78910111213
14151617181920
21222324252627
282930

控制面板

您好,欢迎到访网站!
  查看权限
广告2

退出请按Esc键