delete project with modal in laravel

2019-09-17 09:54发布

问题:

I have a delete button beside my projects that shows a popup modal for confirmation whenever the button is clicked on. I want the yes button in the modal to then delete the project whenever this button is clicked on.

I'm calling the modal into the projects/show view with @include. The modal does appear when the button is clicked using the following jquery but the yes button when pressed is not deleting the project.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


<script>
$(document).ready(function() {

   $(".delete").on("submit", function(e){

       e.preventDefault();

       $('#myModal').modal('show'); 


    });

});

The delete button beside projects:

  {!! Form::open(['route' => ['projects.destroy', $projects->id], 'class' => 'delete', 'method' => 'DELETE']) !!}

           {!!Form::button('<span class="glyphicon glyphicon-remove"></span>', ['class' => 'btn btn-danger btn-md', 'type' => 'submit'])!!}

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

Modal code:

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog modal-md" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title text-center" id="myModalLabel">Delete Confirmation</h4>
      </div>
      <div class="modal-body text-center">
        Are you sure you want to delete this project?
      </div>
      <div class="modal-footer">
        <button type="submit" id="delete-btn" class="btn btn-default" >Yes</button>

        <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
      </div>
    </div>
  </div>
</div>

ProjectController:

<?php

namespace App\Http\Controllers;

use App\project;
use App\Http\Requests;
use Illuminate\Http\Request;
use Session;

class ProjectsController extends Controller
{

 public function destroy($id){

        $project = Project::find($id);

        $project->delete();

        Session::flash('success', 'The project was successfully deleted!');

        return redirect()->route('projects.show', $project->project_id);

    }

}

回答1:

Change the submit button in your modal to this:

{!! Form::open(['route' => ['projects.destroy', $projects->id], 'class' => 'delete', 'method' => 'DELETE']) !!}

<button type="submit" id="delete-btn" class="btn btn-default" >Yes</button>

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

The best solution is to remove your implementation of the delete button you have now and make it a normal button. Let that button pop up the modal and replace your "Yes" button with an actual remove button like I did above.