Laravel在我看来的警报中确认删除

时间:2019-03-07 05:24:18

标签: javascript php laravel bootstrap-4

这应该是一个简单的任务,我还没有完全掌握laravel。 我有我的控制器视图和模型设置。我想使用users.destroy路由删除数据库中的行。但是我想以某种方式做到这一点。我想在页面的警报区域中显示警报,要求确认删除某个用户。我假设我需要将会话中的用户ID传递给警报,以在单击删除按钮时确认我的删除。 如果我单击确认它调用了user.destroy,请单击1按钮在页面顶部打开一个警报。

查看:

<div class="container">
  <div class="row justify-content-center">
    <div class="col-md-12">
      <div class="card">
        <div class="card-header">
          <h4>View All Users</h4>

          @if(session()->get('success'))
          <div class="alert alert-success">
            {{ session()->get('success') }}
          </div>
          @endif
          @if(session()->get('danger'))
          <div class="alert alert-danger">
            {{ session()->get('danger') }}
          </div>
          @endif
        </div>
        <div class="card-body">
          <div class="text-center my-2">
            <a href="{{ route('register') }}" class="btn btn-primary">New User</a>
          </div>
          <div>
            <table class="table table-striped table-bordered">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Username</th>
                  <th colspan="2">Actions</th>
                </tr>
              </thead>
              <tbody>
                @foreach($users as $user)
                <tr>
                  <th>{{$user->id}}</th>
                  <td>{{$user->name}}</td>
                  <td>{{$user->email}}</td>
                  <td>{{$user->username}}</td>
                  <td class="text-center">
                    <a href="{{ route('users.show', $user->id) }}" class="btn btn-primary mr-3">Show</a>
                    <a href="{{ route('users.edit', $user->id) }}" class="btn btn-info text-white ml-3">Edit</a>
                    <a href="#" class="btn btn-danger">Delete</a>
                  </td>
                </tr>
                @endforeach
              </tbody>
            </table>

控制器

public function destroy($id)
{
    User::find($id)->delete();
    return redirect()->route('users.index')->with('success','User Deleted');
}

路线:

Route::resource('users', 'UserController');

5 个答案:

答案 0 :(得分:0)

<div class="container">
<div class="row justify-content-center">
    <div class="col-md-12">
        <div class="card">
            <div class="card-header">
                <h4>View All Users</h4>

                @if(session()->get('success'))
                    <div class="alert alert-success">
                        {{ session()->get('success') }}
                    </div>
                @endif
                @if(session()->get('danger'))
                    <div class="alert alert-danger">
                        {{ session()->get('danger') }}
                    </div>
                @endif
            </div>
            <div class="card-body">
                <div class="text-center my-2">
                    <a href="{{ route('register') }}" class="btn btn-primary">New User</a>
                </div>
                <div>
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Username</th>
                                <th colspan="2">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($users as $user)
                            <tr>
                                <th>{{$user->id}}</th>
                                <td>{{$user->name}}</td>
                                <td>{{$user->email}}</td>
                                <td>{{$user->username}}</td>
                                <td class="text-center">
                                    <a href="{{ route('users.show', $user->id) }}" class="btn btn-primary mr-3">Show</a>
                                    <a href="{{ route('users.edit', $user->id) }}" class="btn btn-info text-white ml-3">Edit</a>
                                    <a href="javascript:;" rel="{{ route('users.delete', $user->id) }}" class="btn btn-danger deleteUser">Delete</a>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                    </table>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).on('click','.deleteUser',function() {
        var url = $(this).attr('rel');
        if(confirm("Are you sure you want to delete this?")){
           window.location.href = url
        }
        else{
            return false;
        }
    })
</script>


or
you can use any plugin like
http://myclabs.github.io/jquery.confirm/
http://bootboxjs.com/

In controller
```php

    public function deleteposts(Request $request)
    { 
         // your delete code is here
           $request->session()->flash('success', 'Post deleted sucessfully');
           return redirect()->back();                  
    }


here you setting success message

答案 1 :(得分:0)

在下面添加链接以删除记录

   <a href="{{ route('users.delete', $user->id) }}" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>

答案 2 :(得分:0)

您可以简单地在代码中使用onclick函数,例如

status

答案 3 :(得分:0)

始终尝试使用 DELETE 方法删除资源,这是最佳方法和最佳实践


<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>View All Users</h4>

                    @if(session()->get('success'))
                        <div class="alert alert-success">
                            {{ session()->get('success') }}
                        </div>
                    @endif
                    @if(session()->get('danger'))
                        <div class="alert alert-danger">
                            {{ session()->get('danger') }}
                        </div>
                    @endif
                </div>
                <div class="card-body">
                    <div class="text-center my-2">
                        <a href="{{ route('register') }}" class="btn btn-primary">New User</a>
                    </div>
                    <div>
                        <table class="table table-striped table-bordered">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Email</th>
                                    <th>Username</th>
                                    <th colspan="2">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($users as $user)
                                <tr>
                                    <th>{{$user->id}}</th>
                                    <td>{{$user->name}}</td>
                                    <td>{{$user->email}}</td>
                                    <td>{{$user->username}}</td>
                                    <td class="text-center">
                                        <a href="{{ route('users.show', $user->id) }}" class="btn btn-primary mr-3">Show</a>
                                        <a href="{{ route('users.edit', $user->id) }}" class="btn btn-info text-white ml-3">Edit</a>
                                        <form method="POST" action="{{ route('users.delete', $user->id) }}">
                                            @csrf // or hidden field
                                            <input name="_method" type="hidden" value="DELETE">
                                            <button type="submit" class="btn btn-xs btn-danger btn-flat show_confirm" data-toggle="tooltip" title='Delete'> <i class="fa fa-trash"> </i></button>
                                        </form>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>  
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script type="text/javascript">
    $('.show_confirm').click(function(e) {
        if(!confirm('Are you sure you want to delete this?')) {
            e.preventDefault();
        }
    });
</script>

如果您使用的是Laravel collective HTML,则可以替换该表单标签

答案 4 :(得分:0)

这只是一个例子,我正在考虑将您的模型设为User.php

如果要使用图标,只需添加超赞的CSS字体

打开您的User.php模型并粘贴以下代码

/**
    * @function     tableActionButtons
    * @author       Manojkiran <manojkiran10031998@gmail.com>
    * @param        string  $fullUrl
    * @param        integer  $id
    * @param        string  $titleValue
    * @param        array  $buttonActions
    * @usage        Generates the buttons
    * @version      1.0
    **/
    /*
    NOTE:

    if you want to show tooltip you need the JQUERY JS and tooltip Javascript

    if you are not well in JavaScript Just Use My Function toolTipScript()



    |--------------------------------------------------------------------------
    | Generates the buttons
    |--------------------------------------------------------------------------
    |Generates the buttons while displaying the table data in laravel
    |when the project is bigger and if you are laravel expert you this.
    |But if you are the learner just go with basic
    |
    |Basically It Will generate the buttons for show edit delete record with the default
    |Route::resource('foo',FooController);
    |
    |//requirements
    |
    |//bootstrap --version (4.1.3)
    |//  <link rel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="" crossorigin="">
    |//fontawesome --version (5.6.0(all))
    |//<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.0/css/all.css" integrity="" crossorigin="">
    |
    |if you want to show tooltip you nee the jquery and tooltip you need these js and toottipscript javascript or use my function toolTipScript
    |
    |//jquery
    |// <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    |//popper js
    |// <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
    |//bootstrap js
    |// <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
    |
    |usage
    |option1:
    |tableActionButtons(url()->full(),$item->id,$item->name);
    |this will generate all the buttons
    |
    |option2:
    |tableActionButtons(url()->full(),$item->id,$item->name,['edit',delete]);
    |this will generate edit and delete the buttons
    |
    |option3:
    |tableActionButtons(url()->full(),$item->id,$item->name,['edit',delete,delete],'group');
    |this will generate all the buttons with button grouping
    |
    |option4:
    |tableActionButtons(url()->full(),$item->id,$item->name,['show','edit','delete'],'dropdown');
    |this will generate all the buttons with button dropdown
    |
    */

    public static  function tableActionButtons($fullUrl, $id, $titleValue, $buttonActions = ['show', 'edit', 'delete'], $buttonOptions = '', $encryptId = false)
    {
        $fullUrl = strtok($fullUrl, '?');
        if ($encryptId) {
            $id = Crypt::encrypt($id);
        }
        // dd(get_class_methods(HtmlString::class));

        //Value of the post Method
        $postMethod = 'POST';
        //if the application is laravel then csrf is used

        $token = csrf_token();

        //NON laravel application
        // if (function_exists('csrf_token'))
        // {
        //   $token = csrf_token();
        // }elseif (!function_exists('csrf_token'))
        // //else if the mcrypt id is used if the function exits
        //     {
        //         if (function_exists('mcrypt_create_iv'))
        //         {
        //             // if the mcrypt_create_iv id is used if the function exits the set the token
        //             $token = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
        //         }
        //         else{
        //             // elseopenssl_random_pseudo_bytes is used if the function exits the set the token
        //             $token = bin2hex(openssl_random_pseudo_bytes(32));
        //         }
        //     }

        //action button Value
        //(url()->full()) will pass the current browser url to the function[only aplicable in laravel]
        $urlWithId  = $fullUrl . '/' . $id;
        //Charset UsedByFrom
        $charset = 'UTF-8';

        // Start Delete Button Arguments
        //title for delete functions
        $deleteFunctionTitle = 'Delete';
        //class name for the deletebutton
        $deleteButtonClass = 'btn-delete btn btn-xs btn-danger';
        //Icon for the delete Button
        $deleteButtonIcon = 'fa fa-trash';
        //text for the delete button
        $deleteButtonText  = 'Delete';
        //dialog Which needs to be displayes while deleting the record
        $deleteConfirmationDialog = 'Are You Sure you wnat to delete ' . $titleValue;

        $deleteButtonTooltopPostion = 'top';
        // End Delete Button Arguments


        // Start Edit Button Arguments
        //title for Edit functions
        $editFunctionTitle = 'Edit';
        $editButtonClass = 'btn-delete btn btn-xs btn-primary';
        //Icon for the Edit Button
        $editButtonIcon = 'fa fa-edit';
        //text for the Edit button
        $editButtonText  = 'Edit';
        $editButtonTooltopPostion = 'top';
        // End Edit Button Arguments


        // Start Show Button Arguments
        //title for Edit functions
        $showFunctionTitle = 'Show';
        $showButtonClass = 'btn-delete btn btn-xs btn-primary';
        //Icon for the Show Button
        $showButtonIcon = 'fa fa-eye';
        //text for the Show button
        $showButtonText  = 'Show';
        $showButtonTooltopPostion = 'top';
        // End Show Button Arguments
        //Start Arguments for DropDown Buttons
        $dropDownButtonName = 'Actions';
        //End Arguments for DropDown Buttons




        $showButton = '';
        $showButton .= '
                <a href="' . $fullUrl . '/' . $id . '"class="' . $showButtonClass . '"data-toggle="tooltip"data-placement="' . $showButtonTooltopPostion . '"title="' . $showFunctionTitle . '-' . $titleValue . '">
                    <i class="' . $showButtonIcon . '"></i> ' . $showButtonText . '
                </a>
            ';

        $editButton = '';
        $editButton .= '
                    <a href="' . $urlWithId . '/edit' . '"class="' . $editButtonClass . '"data-toggle="tooltip"data-placement="' . $editButtonTooltopPostion . '" title="' . $editFunctionTitle . '-' . $titleValue . '">
                        <i class="' . $editButtonIcon . '"></i> ' . $editButtonText . '
                    </a>
                ';


        $deleteButton = '';
        $deleteButton .= '
                    <form id="form-delete-row' . $id . '"  method="' . $postMethod . '" action="' . $urlWithId . '" accept-charset="' . $charset . '"style="display: inline" onSubmit="return confirm(&quot;' . $deleteConfirmationDialog . '&quot;)">
                        <input name="_method" type="hidden" value="DELETE">
                        <input name="_token" type="hidden" value="' . $token . '">
                        <input name="_id" type="hidden" value="' . $id . '">
                        <button type="submit"class="' . $deleteButtonClass . '"data-toggle="tooltip"data-placement="' . $deleteButtonTooltopPostion . '" title="' . $deleteFunctionTitle . '-' . $titleValue . '">
                            <i class="' . $deleteButtonIcon . '"></i>' . $deleteButtonText . '
                        </button>
                    </form>
                ';


        // $deleteButton = "<a href='index.php?page=de_activate_organization&action_id=$id' onClick=\"return confirm('Are you Sure to De Activate?')\"><span class='label label-success'>" ."Test" . "</span></a>";



        $actionButtons = '';

        foreach ($buttonActions as $buttonAction) {
            if ($buttonAction == 'show') {
                $actionButtons .= $showButton;
            }
            if ($buttonAction == 'edit') {
                $actionButtons .= $editButton;
            }
            if ($buttonAction == 'delete') {
                $actionButtons .= $deleteButton;
            }
        }
        if (empty($buttonOptions)) {
            return  new HtmlString($actionButtons);
        } elseif (!empty($buttonOptions)) {
            if ($buttonOptions == 'group') {

                $buttonGroup = '<div class="btn-group" role="group" aria-label="">
                    ' . $actionButtons . '
                    </div>';
                return new HtmlString($buttonGroup);
            } elseif ($buttonOptions == 'dropdown') {
                $dropDownButton  =
                    '<div class="dropdown">
                          <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            ' . $dropDownButtonName . '
                          </button>
                          <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                          ' . $actionButtons . '
                          </div>
                        </div>
                        ';
                return new HtmlString($dropDownButton);
            } else {
                return  'only <code>group</code> and <code>dropdown</code> is Available ';
            }
        }
    }

现在将其添加到User.php

use Illuminate\Support\HtmlString;

现在打开列表index.blade.php,并在for循环迭代中添加以下行

{{ App\User::tableActionButtons(url()->full(),$user->id,$user->name,['delete'],null,false) }}

如果要多个按钮4rt参数接受数组

{{ App\User::tableActionButtons(url()->full(),$user->id,$user->name,['show','edit,'delete],null,false) }}

如果您遇到任何问题,请在下面评论

希望有帮助