Registration Form Submit Laravel Custom Validation with Ajax (CRUD)

Sandipan Kr Bag Mar 02, 2024
Registration Form Submit Laravel Custom Validation with Ajax (CRUD)

Sure, let's break down the code and understand each part:

1. HTML Form: The HTML form is used to collect user data for registration. It includes fields for name, email, password, password confirmation, selecting user type, and uploading a photo. The form is submitted to the route `registration_form` using AJAX when the submit button is clicked.

2. AJAX Request: The jQuery script sends an AJAX request when the form is submitted. It prevents the default form submission behavior using `event.preventDefault()` and creates a `FormData` object to send form data asynchronously to the server.

3. Controller Method (`form_submit`): This method handles the form submission. It first validates the incoming request data using Laravel's validation system. If validation fails, it returns JSON response with validation errors. If validation passes, it creates a new `User` instance, populates it with validated data, saves the uploaded photo to the server, and then saves the user to the database.

4. Validation: The validation rules ensure that the required fields are present, the email is unique, the password matches its confirmation, and the uploaded photo meets the specified criteria. Custom error messages are provided for each validation rule.

5. Saving Uploaded Photo: If a photo is uploaded, the code checks if a file was uploaded using `$request->hasFile('s_photo')`. If so, it generates a unique filename, moves the uploaded file to the `public/student_photo` directory, and saves the filename in the database.

6. Response: After successful registration, the controller returns a JSON response with `success` set to `true`. If there are any errors, it returns JSON response with `success` set to `false` along with error messages.

7. Route: The route `form_submit` points to the `form_submit` method in the controller.

This code demonstrates a registration form submission process using Laravel, including validation, file upload, and handling responses asynchronously using AJAX. It follows best practices for security and user experience.

 

Migration Laravel Default table :  (User)

   Schema::create('users', function (Blueprint $table)

 {

            $table->id();

            $table->string('name');

            $table->string('email')->unique();

            $table->timestamp('email_verified_at')->nullable();

            $table->string('password');

            $table->string('photo');  // add 

            $table->integer('is_admin'); // add

            $table->rememberToken();

            $table->timestamps();

        });

Html Code :

 <span id="success"></span>

        <span id="error"></span>

        <form id="reg_form">

            @csrf

            <div class="form-group">

                <label for="">Enter Name</label>

                <input type="text" name="name" autocomplete="off" placeholder="Enter Your name"

                    class="form-control">

            </div>


 

            <div class="form-group">

                <label for="">Enter Email</label>

                <input type="email" name="email" autocomplete="nope" placeholder="Enter Your Email"

                    class="form-control">

            </div>


 

            <div class="form-group">

                <label for="">Enter Password</label>

                <input type="password" name="password" autocomplete="off" placeholder="Enter password"

                    class="form-control">

            </div>

 

            <div class="form-group">

                <label for="">Re-Enter Password</label>

                <input type="text" name="password_confirmation" autocomplete="off" placeholder="Re-Enter password"

                    class="form-control">

            </div>


 

            <div class="form-group">

                <label for="">Select User</label>

                <select name="is_admin" id="" class="form-control">

                    <option value="">Select User</option>

                    <option value="0">User</option>

                    <option value="1">Admin</option>

                </select>

            </div>

            <div class="form-group">

                <label for="">Upload Photo</label>

                <input type="file" name="s_photo" class="form-control">

            </div>

            <input type="submit" class="btn btn-success mt-2" id="btn" value="Register">

        </form>

Route : 

Route::post('form_submit',[Controller::class,'form_submit'])->name('registration_form');

Ajax : 

    <script>

        $(document).ready(function() {

       $('#reg_form').submit(function(event) {

                event.preventDefault();

                var formData = new FormData(this);

                //console.log(formData);

                $.ajax({

                    url: "{{ route('registration_form') }}",

                    type: "post",

                    data: formData,

                    dataType: "json",

                    contentType: false, // Not setting contentType because FormData handles it automatically

                    processData: false, // Not processing data because FormData handles it automaticall

                    success: function(response) {

                        // console.log(response.success);

                        if (response.success) {

                            $('#success').text('form submited successfully').css('color',

                                'green');

                            // remove success msg after 2 seconds

                            setTimeout(function() {

                                $('#success').text('');

                            }, 2000);

                            $('#reg_form')[0].reset();

                        } else {

                            // for other error like controller error

                            $('error').text(response.error).css('color', 'red');

                        }

                    },

                    error: function(xhr, status, error) {

                        var response = xhr.responseJSON;                           // Access the response directly as JSON

                    // Check if there are validation errors

                        if (response && response.errors) {

                            // Clear previous errors

                            $('.text-danger').remove();

                            // Loop through the errors and display them next to the respective form fields

                            $.each(response.errors, function(key, value) {

                                $('[name="' + key + '"]').after(

                                    '<div class="text-danger">' + value[0] +

                                    '</div>');

                            });

                         // Remove the error messages after 2 seconds

                            setTimeout(function() {

                                $('.text-danger').fadeOut('slow', function() {

                                    $(this).remove();

                                });

                            }, 5000);


 

                        } else {

                            // Display other types of errors

                            $('#error').text(response.message);


 

                            // Remove the error message after 2 seconds

                            setTimeout(function() {

                                $('#error').fadeOut('slow', function() {

                                    $(this).text('');

                                });

                            }, 2000);

                        }

                    },

            })

            })

        })

    </script>

Controller Code :

import 

 use Illuminate\Support\Facades\Hash;

use Illuminate\Validation\Rules\Password;

public function form_submit(Request $request)

    {


 

        //  validation request

        $request->validate(

            [

                'name' => 'required',

                'email' => 'required|email|unique:users',

                'password' => [

                    'required', 'string', 'confirmed',

                    Password::min(8)->letters()->numbers()->mixedCase()->symbols()

                ],

                'password_confirmation' => 'required',

                's_photo' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',


 

                'is_admin' => 'required|in:0,1',

            ],

            [

                'name.required' => "Enter Your name",

                'email.required' => "Enter your email",

                'email.unique' => "This email is already in use",

                'password.required' => "Enter your password",

                'password_confirmation.required' => "Re-Enter your password",

                's_photo.required' => "Upload your photo",

                'is_admin.required' => "choose User",

   ]

        );

        $data = new User();              // this is model

        $data->name = $request->name;

        $data->email = $request->email;

        $data->password = Hash::make($request->password);

        $data->is_admin = $request->is_admin;

        $data->s_photo = $request->s_photo;


// image store

        if ($request->hasFile('s_photo')) {

            $filename = "student_photo/" . time() . $data->name . "-ocec." . $request->file('s_photo')->getClientOriginalExtension();

            $request->file('s_photo')->move(public_path('student_photo'), $filename);

            $data->s_photo = $filename; // Store the filename in the database

 }


 

        $data->save();

        return response()->json(['success' => true, 'data' => ‘registration successfully’]);

    }


 

 

Share this article

sndp bag

Sandipan Kr Bag

I'm a dedicated full-stack developer, entrepreneur, and the proud owner of ocec.org.in , hailing from the vibrant country of India. My passion lies in creating informative tutorials and sharing valuable tips that empower fellow artisans in their journey. With a deep-rooted love for technology, I've been an ardent enthusiast of PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, Codeigniter, and Bootstrap from their earliest days. My philosophy revolves around the values of hard work and unwavering consistency, driving me to continuously explore, create, and share my knowledge with the tech community.

* Hire Me

0 Comments

Load more Comments

Post a Comment

Hint: Please enter between 80 - 300 characters.
ocec.org.in

helllo