带有 HTML 表单的 Laravel 删除按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46098806/
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-09-14 16:37:21  来源:igfitidea点击:

Laravel delete button with HTML form

phphtmlformslaravellaravel-5

提问by user2519032

I'm using the HTML form, not Laravel Collective.

我使用的是 HTML 表单,而不是 Laravel Collective。

For now I've successfully created a CRUD for a users in my CMS, but one thing bothers me:

现在我已经成功地为我的 CMS 中的用户创建了一个 CRUD,但有一件事困扰着我:

How can I set a Delete button in my list of users, instead of the specific edit page?

如何在我的用户列表中设置删除按钮,而不是特定的编辑页面?

Also, it will be nice when a user clicks on the Delete button to show up confirmation popup for deleting the specific user.

此外,当用户单击“删除”按钮以显示用于删除特定用户的确认弹出窗口时,这会很好。

So, here's my code:

所以,这是我的代码:

The controller:

控制器:

/**
 * Remove the specified resource from storage.
 *
 * @param  int  $id
 * @return \Illuminate\Http\Response
 */
public function destroy($id)
{
    $user = User::findOrFail($id);
    $user->delete();

    return redirect('/admin/users'); 
}

The list of users page:

用户列表页面:

@extends('layouts.backend')

@section('content')
  <h1>Users</h1>
  <a class="btn btn-primary" href="/admin/users/create">Create new user</a>
  <table class="table">
    <thead>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
        <th>Role</th>
        <th>Status</th>
        <th>Created</th>
        <th>Updated</th>
        <th>Operations</th>
      </tr>

    </thead>
    <tbody>
      @if($users)
        @foreach($users as $user)
          <tr>
            <td>{{$user->id}}</td>
            <td>{{$user->name}}</td>
            <td>{{$user->email}}</td>
            <td>{{$user->role ? $user->role->name : 'User has no role'}}</td>
            <td>{{$user->status == 1 ? 'Active' : 'Not active'}}</td>
            <td>{{$user->created_at->diffForHumans()}}</td>
            <td>{{$user->updated_at->diffForHumans()}}</td>
            <td>
              <a href="/admin/users/{{$user->id}}/edit" class="btn btn-primary">Edit</a>
              <a class="btn btn-danger" href="">Delete</a> // HOW TO ACHIEVE THIS?
            </td>
          </tr>
        @endforeach
      @endif
    </tbody>
  </table>

@endsection

The specific edit user page:

具体编辑用户页面:

@extends('layouts.backend')

@section('content')
  <h1>Edit user</h1>
  <form method="POST" action="/admin/users/{{$user->id}}">
    {{ csrf_field() }}
    {{ method_field('PATCH') }}

    <div class="form-group">
      <label>Name:</label>
      <input type="text" name="name" class="form-control" value="{{$user->name}}">
    </div>

    <div class="form-group">
      <label>Email:</label>
      <input type="text" name="email" class="form-control" value="{{$user->email}}">
    </div>

    <div class="form-group">
      <label>Role:</label>
      <select name="role_id" class="form-control">
        @if($user->role_id == 1)
          <option value="1" selected>Administrator</option>
          <option value="2">Editor</option>
        @else
          <option value="1">Administrator</option>
          <option value="2" selected>Editor</option>
        @endif
      </select>
    </div>

    <div class="form-group">
      <label>Status:</label>
      <select name="status" class="form-control">
        @if($user->status == 1)
          <option value="1" selected>Active</option>
          <option value="0">Not active</option>
        @else
          <option value="1">Active</option>
          <option value="0" selected>Not active</option>
        @endif
      </select>
    </div>

    <div class="form-group">
      <label>Password</label>
      <input type="password" name="password" class="form-control" value="{{$user->password}}">
    </div>

    <div class="form-group">
      <input type="submit" name="submit" value="Update user" class="btn btn-primary">
    </div>
  </form>

  <form id="delete-form" method="POST" action="/admin/users/{{$user->id}}">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}

    <div class="form-group">
      <input type="submit" class="btn btn-danger" value="Delete user">
    </div>
  </form>

  @include('inc.errors')
@endsection

The route:

路线:

Route::group(['middleware'=>'admin'], function(){
     Route::resource('admin/users', 'AdminUsersController');

     Route::get('/admin', function(){
       return view('admin.index');
     });
    // Route::resource('admin/posts', 'AdminPostsController');
});

回答by DevK

It's not obvious from the code you posted, but your DELETEroute expects DELETEmethod. As it should!

从您发布的代码中并不明显,但您的DELETE路线需要DELETE方法。正如它应该!

But on your list you're trying to access it with GETmethod.

但是在您的列表中,您正在尝试使用GET方法访问它。

Really you should just reuse the code from the edit page, which fakes DELETEmethod already.

实际上,您应该重用编辑页面中的代码,该代码DELETE已经伪造了方法。

Something like this:

像这样的东西:

...
<td>
    <a href="/admin/users/{{$user->id}}/edit" class="btn btn-primary">Edit</a>
    <form method="POST" action="/admin/users/{{$user->id}}">
        {{ csrf_field() }}
        {{ method_field('DELETE') }}

        <div class="form-group">
            <input type="submit" class="btn btn-danger delete-user" value="Delete user">
        </div>
    </form>
</td>
...

...
// Mayank Pandeyz's solution for confirmation customized for this implementation
<script>
    $('.delete-user').click(function(e){
        e.preventDefault() // Don't post the form, unless confirmed
        if (confirm('Are you sure?')) {
            // Post the form
            $(e.target).closest('form').submit() // Post the surrounding form
        }
    });
</script>

回答by Mayank Pandeyz

As you have stated it will be nice when a user clicks on the Delete button to show up confirmation popup for deleting the specific user. For this you have to use jqueryand ajax. Change the following code:

正如您所说,当用户单击“删除”按钮以显示用于删除特定用户的确认弹出窗口时会很好。为此,您必须使用jqueryajax。更改以下代码:

<a class="btn btn-danger" href="">Delete</a>

to

<a class="btn btn-danger delete_user" href="javascript:void(0);" id="{{$user->id}}">Delete</a>

and put an event listener like:

并放置一个事件侦听器,例如:

$('.delete_user').click(function(){
  if( confirm('Are you sure?') )
  {
    var id = $(this).attr('id');
    // Make an ajax call to delete the record and pass the id to identify the record
  }
});

回答by AddWeb Solution Pvt Ltd

You can update your code like:

您可以更新您的代码,如:

<a class="btn btn-danger" href="/admin/users/{{$user->id}}/delete" >Delete</a>

ORyou should delete user using route name like:

或者您应该使用路由名称删除用户,例如:

<a href="{{ route('admin.user.delete', [$user->id]) }}" class="btn btn-xs btn-danger" onclick="return confirm('Are you sure?')">Delete</a>

回答by fico7489

option with "laravel form helper" and jquery

带有“laravel 表单助手”和 jquery 的选项

<div class="actions">
    <a href="#" class="list-icons-item delete-action">
        <i class="icon-trash"></i>
    </a>
    {{ Form::open(['url' => route('admin.users.destroy', $user), 'method' => 'delete']) }}
    {{ Form::close() }}
</div>


<script>
    $(document).ready(function () {
        $('.delete-action').click(function (e) {
            if (confirm('Are you sure?')) {
                $(this).siblings('form').submit();
            }

            return false;
        });
    });
</script>