简体   繁体   中英

Call controller with href on Laravel

I'm trying to call controller with href, but I'm getting error, I need pass a parameter. 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

The link_to_action() helper generates an actual HTML link, which is an <a> tag. 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:

<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. 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. Just change Story story to $id and it should be good.

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:

<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:

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

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

Hope it helps.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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