在Laravel资源路由中如何使用GET请求直接删除资源

注:本代码片段适用于Laravel 5。

routes.php文件顶部添加如下代码片段并将该文件中所有Route::resourceRoute::resources替换为Route::deletableRoute::deletables

use Illuminate\Routing\Router;

Router::macro('deletable', function($name, $controller, $options = []) {
    $this->resource($name, $controller, $options);
    $this->get($name."/{{$name}}/delete", [
        'as' => str_replace('/', '.', (Route::getLastGroupPrefix()==''?'':
            Route::getLastGroupPrefix().'.').$name).'.delete',
        'uses' => $controller.'@destroy',
    ]);
});

Router::macro('deletables', function($deletables) {
    foreach ($deletables as $name => $controller) {
        $this->deletable($name, $controller);
    }
});

这样,一个额外的GET路由会生效,用于直接删除资源,你将对自己的确认提示负责。

学院君 has written 680 articles

资深PHP工程师,Laravel学院院长

One thought on “在Laravel资源路由中如何使用GET请求直接删除资源

  1. Woody says:

    不用这么复杂,直接写下面就可以:

    Route::resource(‘pages’, ‘PageController’,array(
    ‘names’ =>
    array(‘create’ => ‘pages.create’,
    ‘index’=>’pages.index’,
    ‘store’=>’pages.store’,
    ‘edit’=>’pages.edit’,
    ‘update’=>’pages.update’,
    ‘destroy’=>’pages.delete’,
    )));

    Route::get(‘pages/{id}/delete’, [
    ‘as’ => ‘pages.delete’,
    ‘uses’ => ‘PageController@destroy’,
    ]);

发表评论

标记为*的字段是必填项(邮箱地址不会被公开)

你可以使用这些HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>