⌘K
Noting Found

View all related articles

Using Google reCAPTCHA with Laravel 8 and Laravel-Livewire

Laravel 3 mins read

It seems there is an updated version of this article.

Read Article

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

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

    Or

    1laravel new recaptcha-app

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

    1npm 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.

    1DB_CONNECTION=mysql
    2DB_HOST=127.0.0.1
    3DB_PORT=3306
    4DB_DATABASE=recaptcha_app
    5DB_USERNAME=database_username
    6DB_PASSWORD=database_password

    Step 3: Create Contact Model

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

    1php 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

    1public function up()
    2{
    3 Schema::create('contacts', function (Blueprint $table) {
    4 $table->id();
    5 $table->string('email');
    6 $table->text('body');
    7 $table->timestamps();
    8 });
    9}

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

    1class Contact extends Model
    2{
    3 use HasFactory;
    4 
    5 protected $fillable = ['email', 'body'];
    6}

    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:

    1php 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.

    1composer 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.

    1 
    2 
    3<html>
    4<head>
    5 ...
    6 @livewireStyles
    7</head>
    8<body>
    9 ...
    10 @livewireScripts
    11</body>
    12</html>

    You can alternatively use the tag syntax.

    1<livewire:styles />
    2...
    3<livewire:scripts />

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

    1php artisan livewire:publish --config
    1php 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:

    1php artisan livewire:make contact

    This command will generate 2 files,

    1CLASS: app/Http/Livewire/Contact.php
    2VIEW: 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:

    1Route::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

    1Route::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

    1CAPTCHA_SITE_KEY=xxxx
    2CAPTCHA_SECRET_KEY=xxxx

    and in contact.blade.php

    1<form wire:submit.prevent="store">
    2 <div class=" mt-5">
    3 <label class="block uppercase tracking-wide text-grey-darker text-gray-600 text-lg font-bold mb-2"
    4 for="email">
    5 {{__('Email Address')}}
    6 </label>
    7 <input type="text"
    8 name="email"
    9 wire:model.debounce.365ms="email"
    10 placeholder="{{__('Enter Your Email address')}}"
    11 class="border p-3 rounded form-input focus:outline-none w-full shadow-md focus:shadow-lg transition duration-150 ease-in-out"
    12 value="{{old('email')}}">
    13 @error('email')
    14 <p class="text-red-700 font-semibold mt-2">
    15 {{$message}}
    16 </p>
    17 @enderror
    18 </div>
    19 
    20 <div class=" mt-5">
    21 <label class="block uppercase tracking-wide text-grey-darker text-gray-600 text-lg font-bold mb-2">
    22 {{__('Your message')}}
    23 </label>
    24 <textarea name="body" id=""
    25 cols="10"
    26 rows="6"
    27 wire:model.debounce.365ms="body"
    28 placeholder="{{__('Enter Your Message')}}"
    29 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>
    30 @error('body')
    31 <p class="text-red-700 font-semibold mt-2">
    32 {{$message}}
    33 </p>
    34 @enderror
    35 </div>
    36 
    37 <button type="submit"
    38 data-sitekey="{{env('CAPTCHA_SITE_KEY')}}"
    39 data-callback='handle'
    40 data-action='submit'
    41 class="g-recaptcha some-button-style">
    42 Submit
    43 </button>
    44</form>

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

    1<script src="https://www.google.com/recaptcha/api.js?render={{env('CAPTCHA_SITE_KEY')}}"></script>
    2<script>
    3 function handle(e) {
    4 grecaptcha.ready(function () {
    5 grecaptcha.execute('{{env('CAPTCHA_SITE_KEY')}}', {action: 'submit'})
    6 .then(function (token) {
    7 @this.set('captcha', token);
    8 });
    9 })
    10 }
    11</script>

    and in your Contact Component do the following

    1...
    2public $captcha = 0;
    3 
    4public function updatedCaptcha($token)
    5{
    6 $response = Http::post('https://www.google.com/recaptcha/api/siteverify?secret=' . env('CAPTCHA_SECRET_KEY') . '&response=' . $token);
    7 $this->captcha = $response->json()['score'];
    8 
    9 if (!$this->captcha > .3) {
    10 $this->store();
    11 } else {
    12 return session()->flash('success', 'Google thinks you are a bot, please refresh and try again');
    13 }
    14 
    15}
    16public function store()
    17{
    18 // store the contact information
    19}
    20...

    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:

    1php 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 | Technical Writer

    Oussama is an experienced full-stack web developer with a strong focus on Laravel. He's passionate about crafting web applications with Filament and the TALL Stack. With 8+ years of experience, and he's a dedicated open-source contributor.

    Comments

    Join our newsletter

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

    We care about the protection of your data. Read our Privacy Policy.