PHP Laravel 6 SweetAlert jQuery Ajax Delete Rows Example

Today, We want to share with you PHP Laravel 6 SweetAlert jQuery Ajax Delete Rows Example.In this post we will show you Laravel 6 jQuery Ajax CRUD Example with Sweet Alert, hear for How to use sweet alert for delete confirm in Laravel 6? we will give you demo and example for implement.In this post, we will learn about Ajax SweetAlert for Live Data Deleting Rows in with PHP Laravel 6 with MySQL and jQuery with an example.

PHP Laravel 6 SweetAlert jQuery Ajax Delete Rows Example

There are the Following The simple About Laravel 6 Sweet Alert AJAX CRUD Tutorial Full Information With Example and source code.

As I will cover this Post with live Working example to develop Laravel 6 confirmation box for delete a member from database example, so the Display Sweet Alert in Laravel 6 using uxweb/sweet-alert is used for this example is following below.

Phase 1: Download laravel

composer create-project --prefer-dist laravel/laravel aitsMGM

Phase 2: Create Database Migration

php artisan make:model School -m

Create a School model and schools table

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateCompaniesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('schools', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('locations');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('schools');
    }
}

app/School.php

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class School extends Model
{
    protected $fillable = [
        'name',
        'locations'
    ];
}

Phase 3: Define routes

routes/web.php

Route::get('/school', '[email protected]')->name('school.index');
Route::get('/schools', '[email protected]_school_data')->name('data');
Route::get('/addschool', '[email protected]')->name('school.view');
Route::post('/addschool', '[email protected]')->name('school.store');
Route::delete('/addschool/{id}', '[email protected]')->name('school.destroy');
Route::get('/addschool/{id}/edit', '[email protected]')->name('school.update');

Phase 4: Create a Laravel 6 Controller

php artisan make:controller SchoolController

app/Http/Controllers/SchoolController.php

<?php
namespace App\Http\Controllers;

use App\School;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SchoolController extends Controller
{
  public function view()
  {
      return view('school.index');
  }

  public function get_school_data(Request $request)
  {
      $schools = School::latest()->paginate(5);

      return Request::ajax() ? 
                   response()->json($schools,Response::HTTP_OK) 
                   : abort(404);
  }

  public function Store(Request $request)
  {
    School::updateOrCreate(
      [
        'id' => $request->id
      ],
      [
        'name' => $request->name,
        'locations' => $request->locations
      ]
    );

    return response()->json(
      [
        'success' => true,
        'message' => 'Data inserted successfully'
      ]
    );
  }

  public function update($id)
  {
    $comapny  = School::find($id);

    return response()->json([
      'data' => $comapny
    ]);
  }
  
  public function destroy($id)
  {
    $school = School::find($id);

    $school->delete();

    return response()->json([
      'message' => 'Data deleted successfully!'
    ]);
  }

}

Phase 5: Create View File

resources/views/layouts/app.blade.php

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>PHP Laravel 6 ajax crud - infinityknow </title>

    <script src="{{ asset('js/app.js') }}" defer></script>
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    
</head>
<body>


        <main class="py-4">
            @yield('content')
        </main>

    </div>
    <script>
        var root_url = <?php echo json_encode(route('data')) ?>;
        var store = <?php echo json_encode(route('school.store')) ?>;
    </script>
    @stack('ajax_crud')
</body>
</html> 

resources/views/school/index.blade.php

@extends('layouts.app')

@section('content')

<div class="container">
   <div class="row justify-content-center">
      <div class="col-md-8">
          <div class="card">
            <a href="javascript:void(0)" class="btn btn-sm btn-outline-danger py-0" style="font-size: 0.8em; width:100px;" id="createNewSchool">Add School</a>
            <table class="table table-bordered">
              <thead>
                  <tr>
                     <th>Name</th>
                     <th>Address</th>
                     <th width="200px">Action</th>
                  </tr>
              </thead>

              <tbody>
              </tbody>

            </table>
              @include('school.modal')
           </div>
        </div>
    </div>
</div>
@endsection

@push('ajax_crud')

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>  
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>

<script src="/js/ajax.js"></script>

@endpush 

resources/views/school/modal.blade.php

<div class="modal fade" id="student-id">
    <div class="modal-dialog">
        <div class="modal-content">
            
            <div class="modal-header">
                <h4 class="modal-title" id="studentCrudModal"></h4>
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
            </div>

            <div class="modal-body">
                <form id="schooldata">

                    <input type="hidden" id="school_id" name="school_id" value="">
                    <input type="text" id="name" name="name" value="">
                    <input type="text" id="locations" name="locations" value="">
                    </label><br>

                    <input type="submit" value="Submit" id="submit" class="btn btn-sm btn-outline-danger py-0" style="font-size: 0.8em;">

                </form>
            </div>

        </div>
    </div>
</div> 

public/js/ajax.js

$(document).ready(function () {
get_school_data()

$.ajaxSetup({
    headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});

//Get all school
function get_school_data() {
    
	$.ajax({
        url: root_url,
        type:'GET',
    	data: { }
	}).done(function(data){
        table_data_row(data.data)
	});
}

//School table row
function table_data_row(data) {

    var	rows = '';
    
	$.each( data, function( key, value ) {
        
	  	rows = rows + '<tr>';
	  	rows = rows + '<td>'+value.name+'</td>';
	  	rows = rows + '<td>'+value.locations+'</td>';
	  	rows = rows + '<td data-id="'+value.id+'">';
                rows = rows + '<a class="btn btn-sm btn-outline-danger py-0" style="font-size: 0.8em;" id="editSchool" data-id="'+value.id+'" data-toggle="modal" data-target="#student-id" rel="noopener noreferrer">Edit</a> ';
                rows = rows + '<a class="btn btn-sm btn-outline-danger py-0" style="font-size: 0.8em;" id="deleteSchool" data-id="'+value.id+'" >Delete</a> ';
                rows = rows + '</td>';
	  	rows = rows + '</tr>';
	});

	$("tbody").html(rows);
}

//Insert school data
$("body").on("click","#createNewSchool",function(e){

    e.preventDefault;
    $('#studentCrudModal').html("Create school");
    $('#submit').val("Create school");
    $('#student-id').modal('show');
    $('#school_id').val('');
    $('#schooldata').trigger("reset");

});

//Save data into database
$('body').on('click', '#submit', function (event) {
    event.preventDefault()
    var id = $("#school_id").val();
    var name = $("#name").val();
    var locations = $("#locations").val();
   
    $.ajax({
      url: store,
      type: "POST",
      data: {
        id: id,
        name: name,
        locations: locations
      },
      dataType: 'json',
      success: function (data) {
          
          $('#schooldata').trigger("reset");
          $('#student-id').modal('hide');
          Swal.fire({
            position: 'top-end',
            icon: 'success',
            title: 'Success',
            showConfirmButton: false,
            timer: 1500
          })
          get_school_data()
      },
      error: function (data) {
          console.log('Error......');
      }
  });
});

//Edit modal window
$('body').on('click', '#editSchool', function (event) {

    event.preventDefault();
    var id = $(this).data('id');
   
    $.get(store+'/'+ id+'/edit', function (data) {
         
         $('#studentCrudModal').html("Edit school");
         $('#submit').val("Edit school");
         $('#student-id').modal('show');
         $('#school_id').val(data.data.id);
         $('#name').val(data.data.name);
         $('#locations').val(data.data.locations);
     })
});

 //DeleteSchool
 $('body').on('click', '#deleteSchool', function (event) {
    if(!confirm("Do you really want to do this?")) {
       return false;
     }

     event.preventDefault();
    var id = $(this).attr('data-id');
 
    $.ajax(
        {
          url: store+'/'+id,
          type: 'DELETE',
          data: {
                id: id
        },
        success: function (response){
          
            Swal.fire(
              'Remind!',
              'School deleted successfully!',
              'success'
            )
            get_school_data()
        }
     });
      return false;
   });

}); 

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about sweet alert php response.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Validate Email and Password Fields on Form Submit Event
  2.   jQuery Check duplicated value in array
  3.   Vue js Multi level sidebar Dropdown menu
  4.   Laravel 6 Sweet Alert Tutorial With Example
  5.   PHP Laravel Join with subquery Query Builder
  6.   Vue.js Alert popup-Dialog Box using PHP and CSS
  7.   Simple JavaScript Form Validation Example
  8.   PHP Convert currency into number to words string to money conversion
  9.   How to Implement Sweet Alert in Laravel Application
  10.   How to Open URL in New Tab using CakePHP