php route resource,[教程]laravel resource 路由详细使用方法

本文介绍了 Laravel 中的 Route::resource 使用方法,通过实例展示了如何创建 TestController 并绑定资源路由。文章详细解释了资源路由的功能,如何访问不同方法对应的操作,并提供了生成 URL 的示例。读者将学习到如何通过 resource 路由简化控制器与路由的绑定,并理解资源路由支持的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的学习方式是,通过自己写一个列子,来学习某个东西,这次的 laravel 也不列外

这次说下,laravel 下的 routes::resource 使用方法,因为我英文水平不是很好,遇到各种坑,后来没辙,上问答社区找大神指点,终于明白了怎么回事

简单说下他的功能吧

我们写一个控制器,写一个方法,就得去 routes 里面绑定一次,其实有时候挺麻烦的,那么这个时候,有没有一个东西,绑定控制器后,下面的方法就不需要绑定了呢?有的,这就是 resource

通过列子来学习

我们新建一个 控制器

php artisan generate:controller TestController

我们要修改下我们生成的控制器,使用命名空间

test 控制器代码如下

// 命名空间

namespace App\Controllers;

use BaseController;

class TestController extends BaseController {

/**

* Display a listing of the resource.

* GET /test

*

* @return Response

*/

public function index()

{

//

echo 'index';

}

/**

* Show the form for creating a new resource.

* GET /test/create

*

* @return Response

*/

public function create()

{

//

}

/**

* Store a newly created resource in storage.

* POST /test

*

* @return Response

*/

public function store()

{

//

}

/**

* Display the specified resource.

* GET /test/{id}

*

* @param int $id

* @return Response

*/

public function show($id)

{

//

}

/**

* Show the form for editing the specified resource.

* GET /test/{id}/edit

*

* @param int $id

* @return Response

*/

public function edit($id)

{

//

}

/**

* Update the specified resource in storage.

* PUT /test/{id}

*

* @param int $id

* @return Response

*/

public function update($id)

{

//

}

/**

* Remove the specified resource from storage.

* DELETE /test/{id}

*

* @param int $id

* @return Response

*/

public function destroy($id)

{

//

}

}

好了,我们来新建我们的路由,App\Controllers\TestController 就是我们刚刚设置的命名空间哦

Route::resource('test','App\Controllers\TestController');

这个时候,你的控制器就与路由绑定了,

我们访问 localhost/tets 如果输出 index ,那么绑定就成功啦!

好了,绑定好了后,我们来讲讲怎么生成 url,因为使用 URL::route() 都是需要输入 路由的名称的,我们这次绑定整个路由,怎么输入名称呢 ?很简单

就我们之前绑定的 test

URL::route('test.index') // 首页

URL::route('test.edit',array('id'=>1))// 编辑

很简单吧,就是你绑定时候的 名称 连接上你的方法名,

!! 注意,在后台使用,路径要写全,如: admin.test.index

然后,resource 只支持下面几种方法来自动绑定

e423a3ea1659efd96f5e11bfc6cf99c1.png

原文出自:袁超博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值