Delete record with Laravel via AJAX

1

I am developing an application in PHP with Laravel and I have in my AlunosController and following method destroy:

public function destroy($id)
{
    $aluno = new Aluno();
    $result = $aluno->find($id)->delete();

    if($result)
        return redirect()->back();
    else
        return 'Falha';
}
So far so good, the function works correctly. The problem is that I decided to use SweetAlert to do my confirm before deletion. It looks like this:

var btnExcluir = $('.btn-danger');
btnExcluir.click(function(event){
    event.preventDefault();
    swal({
        title: "Deseja continuar?",
        text: "O cadastro do aluno será excluído permanentemente!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Sim, excluir!",
        cancelButtonText: "Cancelar",
        closeOnConfirm: false
    }, function(){
        $.ajax({
            url: "/alunos/destroy",
            type: "POST",
            data: {
                id: 8
            },
            dataType: "html",
            success: function () {
                swal("Excluído!", "O cadastro do aluno foi excluído com sucesso.", "success");
            }, error: function(){
                swal("Erro!", "Não foi possível remover o aluno.", "error");
            }
        });
    });
});

I passed the fixed id 8 just for testing with a record that I have, but it is always falling into error.

I have tried to pass the id in the url, tried to use the type DELETE, tried to pass ID_ALUNO_ALU (which is the name of the attribute in the database and in the model) in date instead of id and nothing worked. Anyone who has ever used AJAX in Laravel could give me a light?

To get ahead, the part that interests my view is like this:

@foreach($alunos as $aluno)
<tr>
    <td>{{$aluno['NM_NIS_ALU']}}</td>
    <td>{{$aluno['ST_NOME_ALU']}}</td>
    <td class="text-right">{{$aluno['IDADE']}}</td>
    <td class="text-center">
        {!! Form::open(['route' => ['alunos.destroy', $aluno['ID_ALUNO_ALU']], 'method' => 'delete', 'class' => 'form']) !!}
            <button type="button" class="btn btn-warning btn-xs esconder-acao" data-toggle="modal" data-target="#modalAluno{{$aluno['ID_ALUNO_ALU']}}">Editar</button>
            {!! Form::submit('Excluir', ['class' => 'btn btn-danger btn-xs esconder-acao']) !!}
        {!! Form::close() !!}
    </td>
</tr>
@endforeach

How do I pass the student id to js?

Thank you guys!

    
asked by anonymous 11.05.2017 / 15:06

2 answers

0

You probably defined the verb "delete" in your route file for the specific route, since in your form you defined this method. When you execute the action in Ajax, the request is going as a post. If there is not a post waiting on this route, you will receive a route error not found. Change the dataType to JSON and the request method to "delete".

Laravel has a feature to work with "unofficial" HTTP verbs, which is to put a hidden field with the name _method in the form, to work with DELETE methods, for example. Do the same in the data field of your request.

    
12.05.2017 / 02:54
0

You made 3 errors: the URL of the AJAX request is wrong because it must contain the segment relative to the student ID; you are not reporting the _method key with the DELETE value on the data object; The% w / w that you expect to receive is of type dataType and not json . There is also no need to enter the student ID on the data object if this information will already be contained in the URL and the use of the html event on the elements that have the click class was a bad choice since it only makes it difficult to obtain the form data.

$('.form-aluno-delete').on('submit', function(e) {
    e.preventDefault();

    $.ajax({
        url: $(this).attr('url'),
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function () {
            swal("Excluído!", "O cadastro do aluno foi excluído com sucesso.", "success");
        }, error: function(){
            swal("Erro!", "Não foi possível remover o aluno.", "error");
        }
    });
});

});

@foreach($alunos as $aluno)
<tr>
  <td>{{$aluno['NM_NIS_ALU']}}</td>
  <td>{{$aluno['ST_NOME_ALU']}}</td>
  <td class="text-right">{{$aluno['IDADE']}}</td>
  <td class="text-center">
    {!! Form::open(['route' => ['alunos.destroy', $aluno['ID_ALUNO_ALU']], 'class' => 'form-aluno-delete']) !!}
      <input type="hidden" name="_method" value="DELETE"> 
      <button type="button" class="btn btn-warning btn-xs esconder-acao" data-toggle="modal" data-target="#modalAluno{{$aluno['ID_ALUNO_ALU']}}">Editar</button>
      {!! Form::submit('Excluir', ['class' => 'btn btn-danger btn-xs esconder-acao']) !!}
    {!! Form::close() !!}
</td>
</tr>
@endforeach
    
12.05.2017 / 14:28