Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

php - CRUD Laravel 4 how to link to destroy?

I will destroy my user with a HTML link, but it doesn't seem to generate the correct link, what am i doing wrong?

public function destroy($id)
{
    //Slet brugeren
    $e = new User($id);
    $e->destroy();

    //Log ogs? brugeren ud
    Auth::logout();

    //redrect til forsiden
    Redirect::to("users/create");
}

In my view i call this {{URL::action('UserController@destroy', array($user->id))}}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update 08/21/2017 for Laravel 5.x

The question asks about Laravel 4, but I include this in case people looking for Laravel 5.x answers end up here. The Form helper (and some others) aren't available as of 5.x. You still need to specify a method on a form if you are doing something besides GET or POST. This is the current way to accomplish that:

<form action="/foo/bar" method="POST">
    <input type="hidden" name="_method" value="PUT">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <!-- other inputs... -->
</form>

You can also use {{ method_field('PUT') }} instead of writing out the hidden _method input.

See https://laravel.com/docs/5.4/routing#form-method-spoofing

Original Answer for Laravel 4

I think when you click the link, it is probably sending a GET request to that end point. CRUD in Laravel works according to REST. This means it is expecting a DELETE request instead of GET.

Here's one possibility from a tutorial by Boris Strahija.

    {{ Form::open(array('route' => array('admin.pages.destroy', $page->id), 'method' => 'delete')) }}
        <button type="submit" class="btn btn-danger btn-mini">Delete</button>
    {{ Form::close() }}

This way, you send the request in a form with the DELETE method. The article explains why a traditional link won't work:

You may notice that the delete button is inside a form. The reason for this is that the destroy() method from our controller needs a DELETE request, and this can be done in this way. If the button was a simple link, the request would be sent via the GET method, and we wouldn’t call the destroy() method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...