在Laravel上使用href调用控制器

时间:2019-08-07 11:24:09

标签: php laravel controller

我正在尝试使用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');
    }

错误缺少路线的必需参数:stories.destroy-> error

4 个答案:

答案 0 :(得分:2)

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')

产生相同的结果。

答案 1 :(得分:0)

我可能是错的,但是在html中,您正在传递一个整数,尽管在控制器中,函数期望使用Story对象。只需将Story story更改为$id,就可以了。

无论如何,没有实际错误就不能说更多。

答案 2 :(得分:0)

您应该以这种方式使用它:由于根据laravel函数link_to_action的解释,第一个参数将是控制器功能路径,第二个将是名称,第三个将是必需参数的数组:

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

您也可以从here

获得帮助

答案 3 :(得分:0)

由于您接受$story作为模型对象,因此不必使用Story::find(),也不必在自己的destroy方法中定义$id,将代码更改为:

public function destroy(Story $story)
{
        $story->delete();

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

希望有帮助。

谢谢