首页 > 解决方案 > 在 Laravel 上使用 href 调用控制器

问题描述

我正在尝试使用 href 调用控制器,但出现错误,我需要传递一个参数。我这样做

<a href="{{ link_to_action('StoriesController@destroy', $story->id) }}" class="delete"><i class="material-icons" title="Delete">&#xE872;</i></a>

控制器代码

public function destroy(Story $story)
    {
        $story = Story::find($id);
        $story->delete();

        return redirect('/stories')->with('success', 'Historic Removed');
    }

错误缺少路由所需的参数:story.destroy ->错误

标签: phplaravelcontroller

解决方案


link_to_action()帮助程序生成一个实际的 HTML 链接,它是一个标记<a>。因此,您已经在错误地使用它。

但是,您遇到的错误可能与此无关。

链接到路线的最佳方法是使用route()帮助程序:

<a href="{{ route('index.index', $yourParam) }}">link</a>

和路线定义:

Route::get('/someroute/{:param}', ['uses' => 'IndexController@index', 'as' => 'index.index']);

注意as键,它为这条路线分配了一个名字。你也可以打电话

Route::get(...)->name('index.index')

产生相同的结果。


推荐阅读