简体   繁体   English

在Laravel上使用href调用控制器

[英]Call controller with href on Laravel

I'm trying to call controller with href, but I'm getting error, I need pass a parameter. 我正在尝试使用href调用控制器,但出现错误,我需要传递一个参数。 Im doing like this 我这样做

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

Controller Code 控制器代码

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

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

Error Missing required parameters for Route: stories.destroy -> error 错误缺少路线的必需参数:stories.destroy-> 错误

The link_to_action() helper generates an actual HTML link, which is an <a> tag. link_to_action()帮助器会生成一个实际的HTML链接,它是一个<a>标记。 You're therefore already using it wrong. 因此,您已经错误地使用了它。

However the error you're getting is likely not related to this. 但是,您遇到的错误很可能与此无关。

The best way to link to routes is using the route() helper: 链接到路线的最佳方法是使用route()帮助器:

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

And the route definition: 以及路线定义:

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

Note the as key, it assigns a name to this route. 注意as键,它将为此路由分配一个名称。 You can also call 你也可以打电话

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

which yields the same result. 产生相同的结果。

I might be wrong but in html you're passing an integer, in controller though, function is expecting an object of Story. 我可能是错的,但是在html中,您正在传递一个整数,尽管在控制器中,函数期望使用Story对象。 Just change Story story to $id and it should be good. 只需将Story story更改为$id ,它应该很好。

Anyway, can't say much more without actual error. 无论如何,没有实际错误不能说更多。

You should use it in this way: since according laravel explanation for function link_to_action first param will be controller function path, 2nd will be name and 3rd will be array of required params: 您应该以这种方式使用它:由于根据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>

You can also get help from here 您也可以从这里获得帮助

Since you are accepting $story as model object so you don't have to use Story::find() and also you haven't define $id in your destroy method therefor Change your code to: 由于您接受$story作为模型对象,因此不必使用Story::find() ,也不必在您的destroy方法中定义$id ,将代码更改为:

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

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

Hope it helps. 希望能帮助到你。

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM