MOTOSHARE 🚗🏍️

Rent Bikes & Cars Directly from Owners

Motoshare connects vehicle owners with people who need bikes and cars on rent. Owners earn from idle vehicles, and renters get flexible ride options.

Visit Motoshare

Laravel 8 – Insert record using ajax

Laravel

Hey friends, I came again to all of you with a new article, must follow below steps to create a CRUD in Laravel using ajax.

📚 Step 1 : create a Laravel project using below command.

       composer create-project laravel/laravel Studentsform

📚 Step 2 : Make a model for this, run below command: after running below command you will find a model name Student and one migration 2021_05_01_create_students_table

php artisan make:model Student -m

📚 Step 3 : Create a StudentController now using below command

php artisan make:controller StudentController

📚 Step 4 : Now open migration and add some column in it

Schema::create('students', function(Blueprint $table)) {
	$table->id();
	$table->string('firstname');
	$table->string('lastname');
	$table->string('email');
	$table->string('phone');
	$table->timestamps();
}

📚 Step 5 : Add table name in Student model and also write fillable area for it with your table column name.

    protected $table = 'students';
	protected $fillable = ['firstname','lastname','email','phone'];

📚 Step 6 : now migrate all your migration using below command , before migrating make sure to create a Database for it.

php artisan migrate

📚 Step 7 : And then Open StudentController.php (app/Http/Controllers/StudentController) and create a function name index().

📄 StudentController.php
public function index()
 {
	$students = Student::orderBy('id','DESC')->get();
	return view('students',compact('students'));
 }

📚 Step 8 : Let’s create a route for this. so now open web.php file situated under routes folder and add also controller location within web.php.

📄 web.php
Use App\Http\Controllers\StudentController
Route::get('/students',[StudentController::class,'index']);

📚 Step 9 : Now create a view file under resources/views with name students.blade.php and below code in it

📄 students.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajax Crud</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
</head>
<body>
    <section style="padding-top:60px">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <div class="card">
                        <div class="card-header">
                            Students <a href="#" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#StudentModal">Add New Students</a>
                        </div>
                        <div class="card-body">
                            <table id="studentTable" class="table">
                                <thead>
                                    <tr>
                                        <th>First Name</th>
                                        <th>Last Name</th>
                                        <th>Email</th>
                                        <th>Phone</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($students as $student)
                                        <tr>
                                            <td>{{$student->firstname}}</td>
                                            <td>{{$student->lastname}}</td>
                                            <td>{{$student->email}}</td>
                                            <td>{{$student->phone}}</td>
                                        </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>

    <!-- modal start -->

    <!-- Button trigger modal -->
    <!-- Modal -->
    <div class="modal fade" id="StudentModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Add new student</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
            <form action="" id="studentForm">
                @csrf
                <div class="form-group">
                    <label for="FirstName">First Name</label>
                    <input type="text" class="form-control" id="firstname">
                </div>
                <div class="form-group">
                    <label for="LastName">Last Name</label>
                    <input type="text" class="form-control" id="lastname">
                </div>
                <div class="form-group">
                    <label for="email">Email</label>
                    <input type="text" class="form-control" id="email">
                </div>
                <div class="form-group">
                    <label for="phone">Phone</label>
                    <input type="text" class="form-control" id="phone">
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
            </div>
            
        </div>
        </div>
    </div>
    <script>
        $("#studentForm").submit(function(e){
            e.preventDefault();
            let firstname = $("#firstname").val();
            let lastname = $("#lastname").val();
            let email = $("#email").val();
            let phone = $("#phone").val();
            let _token = $("input[name=_token]").val();

            $.ajax({
                url: "{{route('student.add')}}",
                type:"POST" ,
                data: {
                    firstname:firstname,
                    lastname:lastname,
                    email:email,
                    phone:phone,
                    _token:_token
                },
                success:function(response)
                {
                    if(response){
                        $("#studentTable tbody").prepend('<tr><td>'+response.firstname+'</td><td>'+response.lastname+' </td><td>'+response.email+'</td><td>'+response.phone+'</td></tr>');
                        $("#studentForm")[0].reset();
                        $("#studentModal").modal('hide');
                    }
                }
            });

        });
    </script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.1/dist/umd/popper.min.js" integrity="sha384-SR1sx49pcuLnqZUnnPwx6FCym0wLsk5JZuNx2bPPENzswTNFaQU1RDvt3wT4gWFG" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.min.js" integrity="sha384-j0CNLUeiqtyaRmlzUHCPZ+Gy5fQu0dQ6eZ/xAww941Ai1SxSY+0EQqNXNE6DZiVc" crossorigin="anonymous"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
</body>
</html>

📚 Step 10 : Create another function in StudentController.php

public function addStudent(Request $request)
	{
		$student = new Student();
		$student->firstname = $request->firstname;
		$student->lastname = $request->lastname;
		$student->email = $request->email;
		$student->phone = $request->phone;
		$student->save();
		return response()->json($student);
	}

📚 Step 11 : Now create a route for addStudent() function, so for this open web.php file again

Route::post('/add-student', [StudentController::class,'addStudent'])->name('student.add');

At last fill the data into popup form and you will see that your form is working fine. yay we did it. Let’s congratulate yourself that you create a CRUD using ajax in Laravel 8.

If you find any issue on above steps then feel free to comment. I will feel very happy to resolve your problems in it.

Chandan Kumar