php CRUD Laravel 5 如何链接到资源控制器的销毁?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30299202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:41:35  来源:igfitidea点击:

CRUD Laravel 5 how to link to destroy of Resource Controller?

phplaravellaravel-5

提问by xenish

I have a link

我有链接

<a class="trashButton" href="{{ URL::route('user.destroy',$members['id'][$i]) }}" style="cursor: pointer;"><i class="fa fa-trash-o"></i></a> 

this link is supposed to direct to the destroy method of the Usercontroller , this is my route Route::resource('/user', 'BackEnd\UsersController');

这个链接应该指向 Usercontroller 的 destroy 方法,这是我的路线 Route::resource('/user', 'BackEnd\UsersController');

UserController is a Resource Controller. But at this moment it is directing me to the show method rather than directing to the destroy method

UserController 是一个资源控制器。但此时它正在将我定向到 show 方法而不是定向到 destroy 方法

采纳答案by manix

This is because you are requesting the resources via GET method instead DELETE method. Look:

这是因为您通过 GET 方法而不是 DELETE 方法请求资源。看:

DELETE  /photo/{photo}  destroy     photo.destroy
GET     /photo/{photo}  show    photo.show

Both routes have the same URL, but the header verb identifies which to call. Looks the RESTful table. For example, via ajax you can send a DELETE request:

两条路由具有相同的 URL,但标头动词标识要调用的路由。看起来是RESTful 表。例如,您可以通过 ajax 发送 DELETE 请求:

$.ajax({
    url: '/user/4',
    type: 'DELETE',  // user.destroy
    success: function(result) {
        // Do something with the result
    }
});

回答by BrokenBinary

You need to send a DELETErequest instead of a GETrequest. You can't do that with a link, so you have to use an AJAX request or a form.

您需要发送DELETE请求而不是GET请求。您不能使用链接来做到这一点,因此您必须使用 AJAX 请求或表单。

Here is the generic form method:

这是通用的表单方法:

<form action="{{ URL::route('user.destroy', $members['id'][$i]) }}" method="POST">
    <input type="hidden" name="_method" value="DELETE">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <button>Delete User</button>
</form>

If you're using Laravel 5.1 or laterthen you can use Laravel's built-in helpers to shorten your code:

如果您使用的是Laravel 5.1 或更高版本,那么您可以使用 Laravel 的内置助手来缩短您的代码:

<form action="{{ route('user.destroy', $members['id'][$i]) }}" method="POST">
    {{ method_field('DELETE') }}
    {{ csrf_field() }}
    <button>Delete User</button>
</form>

If you're using Laravel 5.6 or laterthen you can use the new Blade directives to shorten your code even further:

如果您使用的是Laravel 5.6 或更高版本,那么您可以使用新的 Blade 指令进一步缩短您的代码:

<form action="{{ route('user.destroy', $members['id'][$i]) }}" method="POST">
    @method('DELETE')
    @csrf
    <button>Delete User</button>
</form>

You can read more about method spoofing in Laravel here.

您可以在此处阅读有关Laravel 中方法欺骗的更多信息

回答by Damien Labat

I use this template 'resources/views/utils/delete.blade.php'

我使用这个模板'resources/views/utils/delete.blade.php'

<form action="{{ $url or Request::url() }}" method="POST">
    {{ method_field('DELETE') }}
    {{ csrf_field() }}
    <button type='submit' class="{{ $class or 'btn btn-danger' }}" value="{{ $value or 'delete' }}">{!! $text or 'delete' !!}</button>
</form>

Called as this:

调用如下:

@include('utils.delete',array( 'url' => URL::route('user.destroy',$id),'text' => '<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> delete me'))

回答by Denny

If you're looking to do this via a regular link instead of through AJAX or another type of form request you can set up a special route that will respond to a normal GETrequest:

如果您希望通过常规链接而不是通过 AJAX 或其他类型的表单请求来执行此操作,您可以设置一个特殊路由来响应正常GET请求:

In your routes, define this in addition to the resource:

在你的路由中,除了资源之外还定义了这个:

Route::get('user/{site}/delete', ['as' => 'user.delete', 'uses' => 'UserController@destroy']);

In your view:

在您看来:

<a href="{{ route('user.delete', $user->id) }}">Delete this user</a>

In your controller:

在您的控制器中:

public function destroy(User $user)
{
  $user->delete();
  return redirect()->route('users.index');
}

回答by Moppo

If we need to use an anchor to trigger the destroy route, and we don't want to use ajax, we can put a form inside our link, and submit the form using the onclickattribute:

如果我们需要使用anchor来触发destroy路由,又不想使用ajax,可以在link里面放一个表单,使用onclick属性提交表单:

<a href="javascript:void(0);" onclick="$(this).find('form').submit();" >
    <form action="{{ url('/resource/to/delete') }}" method="post">
        <input type="hidden" name="_method" value="DELETE">
    </form>
</a>

回答by Fang DaHong

If you really want to visit the destroy action on delete route by HTML, then there is an approach to use HTTP Method Spoofing which means that you could visit a delete HTTP method by adding a hidden input named _methodwith the value of `"DELETE". Same way can be used for "PUT" and "PATCH" HTTP method.

如果你真的想通过 HTML 访问删除路由上的销毁操作,那么有一种使用 HTTP 方法欺骗的方法,这意味着你可以通过添加一个名为_method“DELETE”的隐藏输入来访问删除 HTTP 方法。相同的方式可用于“PUT”和“PATCH”HTTP 方法。

Below is a sample for DELETE method.

下面是 DELETE 方法的示例。

<form action="/tasks/5" method="POST">
<input type="hidden" name="_method" value="DELETE">
</form>

will get the route

会得到路线

DELETE  /tasks/{id}  destroy     tasks.destroy

if you use laravel collective, you can write this way in your views.

如果你使用laravel集体,你可以在你的观点中这样写。

{!! Form::open(['url' => '/tasks/'.$cat->id, 'method' => 'delete']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}

回答by Gediminas

In case someone came here to find how to replace standard laravel form for delete, from button in it to link, you can just replace:

如果有人来这里寻找如何替换标准 Laravel 表单以进行删除,从其中的按钮到链接,您可以替换:

{!! Form::open(['method' => 'DELETE', 'route' => ['tasks.destroy', $task->id],'onsubmit' => 'return confirm("Are you sure?")', 'id'=>'himan']) !!}

    {!! Form::submit('Delete') !!}

{!! Form::close() !!}

TO

{!! Form::open(['method' => 'DELETE', 'route' => ['tasks.destroy', $task->id],'onsubmit' => 'return confirm("Are you sure?")', 'id'=>'himan']) !!}

    <a href="#" onclick="$(this).closest('form').submit();">Delete</a>

{!! Form::close() !!}

Just replace button with simple <a href="#"...but with onclickattribute to submit the form!

只需用简单<a href="#"...但带有onclick属性的按钮替换按钮即可提交表单!

回答by Hassan Jamal

GETand DELETEBoth routes have the same URL, but the header verb identifies which to call.

GETDELETE两条路由具有相同的 URL,但标头动词标识要调用的路由。

Here are my code snippets for edit and delete. I use bootstrap modal confirmation for delete action

这是我用于编辑和删除的代码片段。我使用引导模式确认进行删除操作

<div class="btn-group">
  <a href="{{ route('locations.edit', $location->id) }}"
   class="btn btn-default btn-sm">
    <i class="fa fa-pencil"></i>
  </a>
  <span class="btn btn-danger btn-sm formConfirm"
      data-form="#frmDelete-{{$location->id}}"
      data-title="Delete Location"
      data-message="Are you sure you want to delete this Location ?">
      <i class="fa fa-times"></i>
  </span>
<form method="POST"
      style="display: none"
      id="frmDelete-{{$location->id}}"
      action="{{ route('locations.destroy' , $location->id) }}">
    {!! csrf_field() !!}
    {{ method_field('DELETE') }}
    <input type="submit">
</form>

BootStrap Modal

引导模式

<div class="modal fade" id="formConfirm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span
                        class="sr-only">Close</span></button>
            <h4 class="modal-title" id="frm_title">Delete</h4>
        </div>
        <div class="modal-body" id="frm_body"></div>
        <div class="modal-footer">
            <button style='margin-left:10px;' type="button" class="btn btn-primary col-sm-2 pull-right"
                    id="frm_submit">Yes
            </button>
            <button type="button" class="btn btn-danger col-sm-2 pull-right" data-dismiss="modal" id="frm_cancel">
                No
            </button>
        </div>
    </div>
</div>

And Finally JS code

最后是JS代码

$('.formConfirm').on('click', function (e) {
  e.preventDefault();
  var el = $(this);
  var title = el.attr('data-title');
  var msg = el.attr('data-message');
  var dataForm = el.attr('data-form');

  $('#formConfirm')
    .find('#frm_body').html(msg)
    .end().find('#frm_title').html(title)
    .end().modal('show');

  $('#formConfirm').find('#frm_submit').attr('data-form', dataForm);
});

$('#formConfirm').on('click', '#frm_submit', function (e) {
  var id = $(this).attr('data-form');
  $(id).submit();
});

回答by Marek Gralikowski

My, non-ajax version. I use it in dropdowns (bootstrap) in resource list (datatables as well). Very short and universal.

我的非 ajax 版本。我在资源列表(以及数据表)的下拉列表(引导程序)中使用它。非常简短和普遍。

Global jQuery method:

全局 jQuery 方法:

$('.submit-previous-form').click(function (e) {
    e.preventDefault();
    $($(this)).prev('form').submit();
});

And then we can use everywhere something like this:

然后我们可以在任何地方使用这样的东西:

{{ Form::open(['route' => ['user.destroy', $user], 'method' => 'delete']) }} {{ Form::close() }}
<a href="#" class="dropdown-item submit-previous-form" title="Delete user"><i class="icon-trash"></i> Delete him</a>

Recommend: It's easy to integrate with confirms scripts for example swal.

推荐:很容易与确认脚本集成,例如 swal。

回答by Patroklo

If you want to use a link, you can use a library I have created that lets people make links that behave like POST, DELETE... calls.

如果你想使用一个链接,你可以使用我创建的一个库,它可以让人们创建行为类似于 POST、DELETE... 调用的链接。

https://github.com/Patroklo/improved-links

https://github.com/Patroklo/improved-links