CRUD using Ajax(jQuery) in Laravel 11

  <?php


namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    public function addStudent(Request $request)
    {
        $file = $request->file("file");

        $fileName = time() . "" . $file->getClientOriginalName();

        $filePath = $file->storeAs("images", $fileName, "public");

        $student = new Student;
        $student->name = $request->name;
        $student->email = $request->email;
        $student->image = $filePath;
        $student->save();
        return response()->json(["result" => "Student data created Successfully."]);
    }

    public function getStudents()
    {
        $students = Student::all();
        return response()->json(["students" => $students]);
    }

    public function getStudentData($id)
    {
        $student = Student::where("id", $id)->get();
        return view("edit-user", ["student" => $student]);
    }

    public function updateStudent(Request $request)
    {
        $student = Student::find($request->id);
        $student->name = $request->name;
        $student->email = $request->email;

        if ($request->file("file")) {
            $file = $request->file("file");
            $fileName = time() . "" . $file->getClientOriginalName();
            $filePath = $file->storeAs("images", $fileName, "public");

            $student->image = $filePath;
        }

        $student->save();

        return response()->json(["result" => "Student data updated successfully."]);
    }

    public function deleteData($id)
    {
        Student::where("id", $id)->delete();
        return response()->json(["result" => "Student data deleted successfully."]);
    }
}
Above File is app\Http\Controllers\StudentController.php File
If code is not run properly then often use "php artisan optimize" command for this practical.





Below File is app\Models\Student.php File
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
    public $timestamps = true;
    protected $table = "students";
    protected $fillable = ["name", "email", "image"];
}





Below File is resources\views\edit-user.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Edit</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-10">
                <div class="card">
                    <div class="card-header">
                        <h2>Update Student Data</h2>
                    </div>
                    <div class="card-body">
                        <img src="{{ asset('storage/') }}/{{ $student[0]->image }}" alt="" width="100px">
                        <form id="update-form">
                            @csrf
                            <input type="text" name="name" value="{{ $student[0]->name }}" placeholder="Enter name" required/>
                            <br><br>
                            <input type="email" name="email" value="{{ $student[0]->email }}" placeholder="Enter email" required/>
                            <br><br>
                            <input type="file" name="file">
                            <input type="hidden" name="id" value="{{ $student[0]->id }}">
                            <br><br>
                            <input type="submit" value="Update Data">
                        </form>
                        <span id="output"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script>
    $(document).ready(function(){
        $("#update-form").submit(function(event){
            event.preventDefault();

            var form = $("#update-form")[0];
            var data = new FormData(form);

            $.ajax({
                url:"{{ route('updateStudent') }}",
                type:"POST",
                data:data,
                processData:false,
                contentType:false,
                success:function(data){
                    $("#output").text(data.result);
                    window.open("/get-students","_self");
                },
                error:function(error){
                    $("#output").text(error.responseText);
                }
            });
        });
    });
</script>





Below File is resources\views\form.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Form</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-10">
                <div class="card">
                    <div class="card-header">
                        <h2>Add Student</h2>
                    </div>
                    <div class="card-body">
                        <form id="my-form" action="" method="POST">
                            @csrf
                            <input type="text" name="name" placeholder="Enter name" required/>
                            <br><br>
                            <input type="email" name="email" placeholder="Enter email" required/>
                            <br><br>
                            <input type="file" name="file" required/>
                            <br><br>
                            <input type="submit" value="Add Student" id="btnSubmit"/>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="output"></div>
    <script>
        $(document).ready(function(){
            $("#my-form").submit(function(event){
                event.preventDefault();

                var form = $("#my-form")[0];
                var data = new FormData(form);

                $("#btnSubmit").prop("disabled",true);

                $.ajax({
                    url:"{{ route('addStudent') }}",
                    type:"POST",
                    data:data,
                    processData:false,
                    contentType:false,
                    success:function(data){
                        // alert(data.result);
                        $("#output").text(data.result);
                        $("#btnSubmit").prop("disabled",false);
                        $("input[type='text']").val("");
                        $("input[type='email']").val("");
                        $("input[type='file']").val("");
                    },
                    error:function(e){
                        console.log(e.responseText);
                        $("#output").text(e.responseText);
                        $("#btnSubmit").prop("disabled",false);
                        $("input[type='text']").val("");
                        $("input[type='email']").val("");
                        $("input[type='file']").val("");
                    }
                });
            });
        });
    </script>
</body>
</html>





Below File is resources\views\students.blade.php File
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Students</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-10">
                <div class="card">
                    <div class="card-header">
                        <h2>Student Data</h2>
                    </div>
                    <div class="card-body">
                        <span id="output"></span>
                        <table class="table table-bordered table-striped table-hovered" id="students-table">
                            <thead>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Image</th>
                                <th>Action</th>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
<script>
    $(document).ready(function(){
        $.ajax({
            url:"{{ route('getStudents') }}",
            type:"GET",
            success:function(data){
                console.log(data);
                if(data.students.length > 0) {
                    for(let i=0;i<data.students.length;i++) {
                        let img = data.students[i]["image"];
                        $("#students-table").append(`<tr>
                            <td>`+(i+1)+`</td>
                            <td>`+(data.students[i]["name"])+`</td>
                            <td>`+(data.students[i]["email"])+`</td>
                            <td>
                                <img src="{{ asset('storage/`+img+`') }}" alt="`+img+`" width="100px" height="100px">
                            </td>
                            <td>
                                <a href="editUser/`+(data.students[i]["id"])+`">Edit</a>
                                <a class="deleteData" data-id="`+(data.students[i]["id"])+`">Delete</a>
                            </td>
                            </tr>`);
                    }
                } else {
                    $("#students-table").append("<tr><td colspan='4'>Data Not Found</td></tr>");
                }
            },
            error:function(error){
                console.log(error.responseText);
            }
        });

        $("#students-table").on("click",".deleteData",function(){
            var id = $(this).attr("data-id");
            var obj = $(this);
            $.ajax({
                url:"/delete-data/"+id,
                type:"GET",
                success:function(data){
                    $(obj).parent().parent().remove();
                    $("#output").text(data.result);
                },
                error:function(error){
                    console.log(error.responseText);
                }
            });
        });
    });
</script>





Below File is routes\web.php File
<?php

use App\Http\Controllers\StudentController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get("/add-student", function () {
    return view("form");
});

Route::controller(StudentController::class)->group(function () {
    Route::post("/add-student", "addStudent")->name("addStudent");
    Route::get("/get-students", function () {
        return view("students");
    });
    Route::get("/get-all-students", "getStudents")->name("getStudents");
    Route::get("/editUser/{id}", "getStudentData")->name("getStudentData");
    Route::post("/update-data", "updateStudent")->name("updateStudent");
    Route::get("/delete-data/{id}", "deleteData");
});




Comments

Popular posts from this blog

CRUD Project (Create | Read | Update | Delete) | Image Upload in Laravel 11