Delete Laravel6x - with Sweetalert2

Asked

Viewed 67 times

-1

As I am beginner using Laravel (version 6x) I am having a problem to perform a Delete, I am using Sweetalert to perform the deletion follows the console error:

POST http://localhost:8000/Atividades/destroy/ 405 (Method Not Allowed)

View:

<button type="submit" id="deletar" onclick="return deletar({{$atividade->id}})"
class="btn btn-sm btn-danger" ><i class="fas fa-trash"></i></button>


    function deletar(id) {
    Swal.fire({
    title: 'Confirma e exclusão?',
    text: "esta ação é irreversivel..",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    cancelButtonText: 'Cancelar',
    confirmButtonText: 'Sim, vou deletar!'
    }).then((result) => {
        if(result.value){
            $.ajax({
                url: `{{route ('atividade.destroy')}}/`,
                type:'POST',
                data: {
                        '_method': 'DELETE',
                        '_token': '{{csrf_token()}}',
                        'id': id

                    },
                success: function (response)  {
                        $('#example2').DataTable().ajax.reload();
                        swal({
                            type:'success',
                            title: 'Sucesso',
                            text: 'Atividade Deletada !!!'
                        });
                    }
            });
        }
    })
}

Controller

public function destroy($id)
{
    $model = Atividade::findOrFail($id);
    $model->delete();
}

Model

class Atividade extends Model
{
   protected $fillable = ['atividade'];
   protected $guarded = ['id', 'created_at', 'update_at'];
   protected $table = 'atividades';
}

Route

Route::group(['middleware' => ['auth'], 'prefix' => 'Atividades'], function() 
{
Route::get('/', 'AtividadesController@index')->name('atividade.home');
Route::post('/store', 'AtividadesController@store')->name('atividade.store');
Route::post('/destroy', 'AtividadesController@destroy')->name('atividade.destroy');
});
  • Are you sure the verb HTTP used by that route is DELETE? Because this error happens when you try to use a route with a verb HTTP different from what it was configured.

  • If the route has set correctly as DELETE tries to change the type of your ajax of POST for DELETE . But keep sending the '_method': 'DELETE' on its date.

  • DELETE http://localhost:8000/Activities/Destroy/ 405 (Method Not Allowed)

  • Friend your route file is showing that it is configured as POST and not delete. Change to Route::delete('/destroy', 'AtividadesController@destroy')->name('atividade.destroy');

  • DELETE http://localhost:8000/Activities/Destroy/ 500 (Internal Server Error) is now just discovering the internal error. Muitoobg

  • Look at the log file.

  • how do I do that?

  • storage/logs/laravel.log

  • Can you help me? [2020-02-28 18:24:24] local.ERROR: Too few Arguments to Function App Http Controllers Activitiesbuncroller::Destroy(), 0 passed and Exactly 1 expected {"userid":1,"Exception":"[Object] (Symfony Component Debug Exception Fatalthrowableerror(code: 0): Too few Arguments to Function App Http Controllers Activitiesdiscount:::Destroy(), 0 passed and Exactly 1 expected at C:xampp htdocs app programming Http Controllers Activitygroup.php:54) [stacktrace]

  • Your route needs a path param which is the ID of who you will remove. So in your ajax you need to inform your route by concatenating with the ID of who you want to remove and not pass it by the request body, or you can remove the parameter from your Destroy method and pick up the ID by the request body.

  • I think this should work: url: `{{route ('atividade.destroy')}}/` + id,

  • There are some more details that are wrong in your route file, I will create an answer fixing everything.

  • Kayo I really appreciate your help, I made the change that you mentioned and generated the error DELETE http://localhost:8000/Activities/Destroy/1 404 (Not Found) and I thank you again with your reply with the correction

  • You updated your route file?

  • updated the route and generated the error Missing required Parameters for [Route: activity.Destroy] [URI: Activities/Destroy/{id}]. (View: C: xampp htdocs programing Resources views activities index.blade.php)

  • Try this on your AJAX: url: `{{route ('atividade.destroy', [$atividade->id])}}`, or url: `{{route ('atividade.destroy', ['id' => $atividade->id])}}`,

  • after I changed the route the error remains even by changing the route in ajax. Missing required Parameters for [Route: activity.Destroy] [URI: Activities/Destroy/{id}]. (View: C: xampp htdocs programing Resources views activities index.blade.php)

Show 12 more comments

1 answer

0

Controller

public function destroy($id)
{
    $model = Atividade::findOrFail($id);
    $model->delete();
}

Route

Route::group(['middleware' => ['auth'], 'prefix' => 'Atividades'], function() 
{
    Route::delete('/destroy/{id}', 'AtividadesController@destroy')->name('atividade.destroy');
});

View

<button type="submit" id="deletar" onclick="return deletar({{$atividade->id}})"
class="btn btn-sm btn-danger" ><i class="fas fa-trash"></i></button>
    function deletar(id) {
    Swal.fire({
    title: 'Confirma e exclusão?',
    text: "esta ação é irreversivel..",
    icon: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    cancelButtonText: 'Cancelar',
    confirmButtonText: 'Sim, vou deletar!'
    }).then((result) => {
        if(result.value){
            $.ajax({
                // Não me recordo bem mas acho que a função "route" recebe um segundo parâmetro que é um array com os parâmetros da sua rota, você pode confirmar isso na documentação.
                url: `{{route ('atividade.destroy')}}/` + `{{ $atividade->id }}`,
                type:'POST',
                data: {
                        '_method': 'DELETE',
                        '_token': '{{csrf_token()}}',
                        'id': id

                    },
                success: function (response)  {
                        $('#example2').DataTable().ajax.reload();
                        swal({
                            type:'success',
                            title: 'Sucesso',
                            text: 'Atividade Deletada !!!'
                        });
                    }
            });
        }
    })
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.