在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 548 articles

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