phplaravellumenlumen-5.2lumen-routing

Lumen: How to delete a record from DB?


Using Lumen, I'm displaying "Tickets". Here's my Tickets.blade.php:

@foreach($tickets as $ticket)
<div>
    <p>{{ $ticket->id }}</p>
    <p>{{ $ticket->content }}</p>
    <button onclick="deleteTicket({{$ticket->id}})">Delete</button>
</div>
@endforeach

So essentially, each time someone clicks delete, it triggers this script:

<script>
    function deleteTicket(id) {
        jQuery.ajax({
            type: "post",
            url: "/tickets/deleteTicket",
            data: id,
            dataType: "text",
            success: function () {
                console.log('deleted!');
            }
        });

    }
</script>

In my routes.php, I have this:

$app->post('tickets/deleteTicket','TicketsController@deleteTicket');

Finally, in my TicketsController.php, I have:

public function deleteTicket($id) {
    $ticket = Ticket::find($id);
    $ticket->delete();

    return redirect('/tickets');
}

The problem I'm getting when I press the button (console):

POST http://example.com/tickets/deleteTicket 404 (Not Found)

I don't understand what I'm doing wrong, and why that method isn't being found. Can anyone help out?

EDIT- I have changed my routes.php to:

$app->get('tickets/deleteTicket/{id}','TicketsController@deleteTicket');

My script looks the same but I changed the "type" to get rather than post.

If I visit, this site: http://mysite/tickets/deleteTicket/1, the ticket will be deleted, and it redirects to tickets page. But if the button is clicked, this error happens:

http://MYSITE/tickets/deleteTicket?id=3 404 (Not Found)

At this point, I'm thinking that I just need to revise my AJAX call to the correct URL, but I want to make sure security is an issue.


Solution

  • Or you can try this :

    routes.php

    $app->get('tickets/deleteTicket/{id}','TicketsController@deleteTicket');
    

    Okay here's your blade : add class to button and remove the function on click. like this one :

    <button class="delete" data-id="{{$ticket->id}}>Delete</button>
    

    And your script :

    $(".delete").on("click", function(e) {
         e.preventDefault();
        var id = $(this).data('id');
        $.ajax({ 
           url : "tickets/deleteTicket/"+id+"",
           type : "get" or "post",
          success: function(data) {
              alert(data);    
           }
        });
    });