Using Google reCAPTCHA with Laravel 8 and Laravel-Livewire

Laravel 3 mins read

Table of Content

    Introduction

    Google reCAPTCHA is a captcha like system. It assures that a computer user is a human. It is the best and most used captcha system available, where users are only required to click on a checkbox and in some cases select some similar images.

    In this article we will discuss how to implement Google reCAPTCHA in Laravel livewire projects. Just follow the below given easy steps to add Google reCAPTCHA into your livewire form, and you are ready to go.

    • Step 1: Download Laravel app
    • Step 2: Add Database Credentials
    • Step 3: Create Contact Model
    • Step 5: Run Migration Command
    • Step 5: Install livewire to your existing project
    • Step 7: Generate livewire Component
    • Step 8: Add Routes
    • Step 9: add Google reCAPTCHA
    • Step 10: Run Development Server

    I will Guide you throw this whole steps, all what I need from you to just bear with me :)

    What is Laravel Livewire?

    Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel.

    Step 1: Download Laravel app

    the first step you're gonna to need is the installation of a fresh Laravel app (if you don't have an existing project) and I will be using Laravel ^8 and Livewire ^2

    composer create-project --prefer-dist laravel/laravel recaptcha-app
    

    Or

    laravel new recaptcha-app
    

    after the installation go well, you need to run NPM installation to scaffold the front-end

    npm install && npm run dev
    

    Step 2: Add Database Credentials

    You need to add the database credentials to store the messages after the user submitting the form.

    In this case I'll be using MySQl as a database driver.

    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=recaptcha_app
    DB_USERNAME=database_username
    DB_PASSWORD=database_password
    

    Step 3: Create Contact Model

    After set up the database, we need to create a new model called Contact by running:

    php artisan make:model Contact -m
    

    The -m Flag is for creating a migration file.

    For the sack of this example I'll keep it simple, I just added an email field and a body

    public function up()
    {
    		Schema::create('contacts', function (Blueprint $table) {
    				$table->id();
    				$table->string('email');
    				$table->text('body');
    				$table->timestamps();
    		});
    }
    

    After that, we add the fillable fields in the Contact model.

    class Contact extends Model
    {
        use HasFactory;
    
        protected $fillable = ['email', 'body'];
    }
    

    Step 5: Run Migration Command

    After we're creating the project, adding the database credentials, and adding the model, we must run the migration command by:

    php artisan migrate
    

    and after the migration, you will see in the contacts' table something like this:

    Step 6: Install livewire to your existing project

    We arrived to the exciting part 😊 which is installing Laravel livewire.

    composer require livewire/livewire
    

    After the installation process completed successfully, We will add the following blade directives in the head tag, and before the end body tag in your template.

    
    
    <html>
    <head>
        ...
        @livewireStyles
    </head>
    <body>
        ...
        @livewireScripts
    </body>
    </html>
    
    

    You can alternatively use the tag syntax.

    <livewire:styles />
    ...
    <livewire:scripts />
    
    

    After that, we need to publish the config file and the Frontend Assets

    php artisan livewire:publish --config
    
    php artisan livewire:publish --assets
    

    Step 7: Generate livewire Component

    After we're successfully installing Livewire into our project, We need to generate a new component:

    php artisan livewire:make contact
    

    This command will generate 2 files,

    CLASS: app/Http/Livewire/Contact.php
    VIEW:  resources/views/livewire/contact.blade.php
    

    Step 8: Add Routes

    Now we need to add some routes into our application to show the contact form.

    In your routes/web.php add the following:

    Route::get('/contact', App\Http\Livewire\Contact::class)->name('contact');
    

    This is the way how livewire deals with route in v2, and if you are running your existing project in v1 you can add the route like this

    Route::livewire('/contact', 'contact')->name('contact');
    

    Step 9: add Google reCAPTCHA

    In this part we will be using reCAPTCHA V3 and all what you need to do is the following:

    First add captcha key and secret into .env file

    CAPTCHA_SITE_KEY=xxxx
    CAPTCHA_SITE_SECRET=xxxx
    

    and in contact.blade.php

    <form wire:submit.prevent="store">
            <div class=" mt-5">
                <label class="block uppercase tracking-wide text-grey-darker text-gray-600 text-lg font-bold mb-2"
                        for="email">
                    {{__('Email Address')}}
                </label>
                <input type="text"
                        name="email"
                        wire:model.debounce.365ms="email"
                        placeholder="{{__('Enter Your Email address')}}"
                        class="border p-3 rounded form-input focus:outline-none w-full shadow-md focus:shadow-lg transition duration-150 ease-in-out"
                        value="{{old('email')}}">
                @error('email')
                    <p class="text-red-700 font-semibold mt-2">
                        {{$message}}
                    </p>
                @enderror
            </div>
    
            <div class=" mt-5">
                <label class="block uppercase tracking-wide text-grey-darker text-gray-600 text-lg font-bold mb-2">
                    {{__('Your message')}}
                </label>
                <textarea name="body" id=""
                            cols="10"
                            rows="6"
                            wire:model.debounce.365ms="body"
                            placeholder="{{__('Enter Your Message')}}"
                            class="border p-2 mt-3 w-full form-textarea shadow-md focus:outline-none focus:shadown-lg transition duration-150 ease-in-out rounded-sm">{{old('body')}}</textarea>
                @error('body')
                    <p class="text-red-700 font-semibold mt-2">
                        {{$message}}
                    </p>
                @enderror
            </div>
    
           <button type="submit"
                  data-sitekey="{{env('CAPTCHA_SITE_KEY')}}"
                  data-callback='handle'
                  data-action='submit'
                   class="g-recaptcha some-button-style">
                   Submit
          </button>
    </form>
    

    after we place the form, we must add google captcha scripts

        <script src="https://www.google.com/recaptcha/api.js?render={{env('CAPTCHA_SITE_KEY')}}"></script>
        <script>
            function handle(e) {
                grecaptcha.ready(function () {
                    grecaptcha.execute('{{env('CAPTCHA_SITE_KEY')}}', {action: 'submit'})
                        .then(function (token) {
                            @this.set('captcha', token);
                        });
                })
            }
        </script>
    

    and in your Contact Component do the following

    ...
    public $captcha = 0;
    
    public function updatedCaptcha($token)
    {
        $response = Http::post('https://www.google.com/recaptcha/api/siteverify?secret=' . env('CAPTCHA_SECRET_KEY') . '&response=' . $token);
        $this->captcha = $response->json()['score'];
    
        if (!$this->captcha > .3) {
            $this->store();
        } else {
            return session()->flash('success', 'Google thinks you are a bot, please refresh and try again');
        }
    
    }
    public function store()
    {
        // store the contact information
    }
    ...
    

    The store method will be fired if the score passes .3 otherwise it returns a message to the user.

    Step 10: Run Development Server

    After setting up all the dependencies, run your development server by:

    php artisan serve
    

    Or any kind of methods you like, such as valet or homestead … Etc

    Conclusion

    In this article we take a look at Google reCAPTCHA and how to implement it using Laravel and Laravel livewire, for more information about google reCAPTCHA you can take a look at the official documentation.

    Thank you for stopping by, and I hope you find something useful.


    Related Tags

    About the Author

    Oussama's Profile Picture
    Oussama
    Full Stack Web Developer

    I'm a full stack web developer and telecommunications engineer who love to share knowledge and build stuff online!


    Comments

    Join Our Newsletter

    Subscribe to Our Newsletter and never miss our offers, latest news, Articles, etc.

    Our news letter sent once a week, every tuesday.