Laravel 8 – Insert record using ajax

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.

Tagged : /

150+ Developer Resources. you must see these resources in 2021.

Hey folks, these are the article, videos and awesome blogs which i am going to prefer you in 2021. these resources will help you a lot. so let’s see below what i am going to provide you with my research.

HTML Resources

#TitleMy Thoughts
1.HTML: <!DOCTYPE> tagYou will love these basics html tag.
2.W3S HTML5 Semantic ElementsGreat quick intro to why everything shouldn’t be in a <div>.
3.MDN HTML elements referencewhat a great info about all html tags. you have to look these explanations once when you are a beginner.
4.New Structural Elements in HTML5This link will help you to understand elements like <time>, <figure>, <article> etc.
5.HTML5 Periodical TableI really like the concept of this website. this website gives me the feel of like chemistry periodic table.
6.Scripts: async, deferIt will give you the best example to embed JS in html files.
7.Learn to Code HTML & CSSIt will really a fast crash course of HTML. You will love it.
8.metatags.ioOne of the best generators to create meta tags for your social media platforms like: Facebook, twitter and LinkedIn etc.
9.getwaves.ioSuch an awesome website to create awesome waves to separate sections in your website.

CSS Resources

#TitleThoughts
10.Bootstrap DocumentationYou are very known of this website if you are using bootstrap in your template. so always use this for bootstrap default class and new changes in latest versions.
11.Specifics on CSS SpecificityGreat breakdown by CSS-Tricks and has nice graphic examples at the end.
12.CSS Box SizingIt will help you to understand, how the box-model works.
13.12 tips for amazing CSS animationSuch and amazing tips on CSS animation with full of brief explanations.
14.CSS Layout and AnimationsYou must read it and it will help you lot on CSS Layout and animations.
15.Net Ninja SASS TutorialWhenever i visit his channel, He gives me a positive vibes to learn new things in a very easy and cool way.
16.Learn Sass In 20 Minutesif you are a beginner about SASS, then must watch this video first.
17.BEM and SASS: A Perfect MatchThis blew my mind when introduced how BEM and SASS could be used together.
18.getbem.comIt gives an overview from the creators of the popular naming convention.
19.BEM by ExampleThis explanation on BEM is really good, but I especially like how they have a short and full versions of the article.
20.MDN Display DocsEverything you could ever want to know about the powerful display property.
21.A Couple of Use Cases for Calc()calc() is one of the more powerful features in CSS and this article shows some great use cases for it.
22.Wes Bos CSS GridYou can’t argue with free and that Wes Bos is one of the best teachers out there for development.
23.CSSmaticCollection of powerful css generators for gradients, border radius, noise texture and box shadows.
24.CSS Tricks Positionafter reading this you will know the power of position property.
25.Can I Use?This site lets you know the browser support for every property out there.
26.yoksel Flex CheatsheetI love the layout and way it lets you visually preview the flexbox properties.
27.The 30 CSS Selectors You Must MemorizeIt such an super article on CSS selectors. I loved it.
28.CSS LintThis tool will check your code and highlight any errors.
29.System Font StackPredefined font fallback stacks that can be plugged into a project.
30.Neumorphism.ioJust follow and you will understand about Neumorphism.
31.Advanced CSS and Sass: Flexbox, Grid, Animations and More!Udemy has great videos on CSS and other courses also.
32.CSS Scroll ShadowsThis tool generates shadows that appear based on scroll position with just CSS!

JavaScript Resources

#TitleMy Thoughts
33.JavaScript in 4 HoursEvery developers should watch this videos on JavaScript intro and other things . very well explained.
34.javascript.infoThis is one of the complete and well explained overview of JS.
35.Code BeautifyIt is such an great tool to beautify your JavaScript.
36.Truthy and Falsy: When All is Not Equal in JavaScriptThis article is a great reference for all the instances that a value might be considered true or false.
37.What the heck is the event loop anyway?watch and understand about event loop in JavaScript.
38.JavaScript LoopsIf I could only read one article to understand common JS loops, this would be the one.
39.MDN JS StringEverything I’d ever want to know about strings and where to use them.
40.Google Hosted Library jQueryyou must bookmark this url to know about latest jQuery CDN script.
41.Public APIsGreat list of public APIs that you can use it very easily in your projects!

Be with us and be safe. you will get more list soon. Let’s share your best content on CSS, JS and Other web technologies.