Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Laravel 8 and Google Autocomplete form tutorial
Christophe
Christophe

Posted on

     

Laravel 8 and Google Autocomplete form tutorial

I wrote this tutorial as this was something I had a hard time to get it right, and documentation was not really clear for me.

I'll explain this basic crud example in Laravel 8 with a Google Autocomplete form. So I combine it with a real-life example. I will also implement a login/register system, which is one of Laravel's strengths.

Get following stuff ready:

1. Create a Laravel project

Create a Laravel project, assuming you have Composer installed. If you don't have composer install or for further documentation, I refer you to the officialLaravel documentation, which is really clear and helpful.

To see if you have Composer installed, you can runcomposer --version in your terminal to see what version you have installed. If not, you should take a look at the documentation 👆.

composercreate-projectlaravel/laravellaravel-googlemaps-autocomplete
Enter fullscreen modeExit fullscreen mode

After everything is installed cd into the project and open with your IDE.

2. Database credentials

Before we can add an authentication system, we should configure our database. Fill in your.env variables and check the connection with your preferred DB manager. On my mac I use Sequel Ace, which I can really recommend. For the live server I use MAMP, which is really easy and straightforward.
For example my.env file looks like this:

DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=8889DB_DATABASE=laravel_googlemaps_autocompleteDB_USERNAME=rootDB_PASSWORD=
Enter fullscreen modeExit fullscreen mode

Yours will look different. TheDB_PORT is the port that MAMP uses for MySQL. Username and password are usually both root, but you should check that out.

Add the database with the same name to your databases in your db-manager.

After you filled in the credentials in your.env file, run your database migrations withphp artisan migrate. You should be able to see that the migration tables were created successfully and these tables should be visible in your db-manager, like this:
Screenshot 2021-04-08 at 12.17.31

3. Authentication (Laravel Breeze)

We want an authentication system where we can login and register.Laravel Breeze is a very handy and lightweight option.

Once everything in the last step is installed successfully, you can install Laravel Breeze via Composer:

composerrequirelaravel/breeze--dev
Enter fullscreen modeExit fullscreen mode

Next steps (copied from the Laravel documentation website) are:

After Composer has installed the Laravel Breeze package, you may run thebreeze:install Artisan command. This command publishes the authentication views, routes, controllers, and other resources to your application. Laravel Breeze publishes all of its code to your application so that you have full control and visibility over its features and implementation. After Breeze is installed, you should also compile your assets so that your application's CSS file is available:

phpartisanbreeze:installnpminstallnpmrundevphpartisanmigrate
Enter fullscreen modeExit fullscreen mode

Runphp artisan serve to run your project and you should seeLogin andRegister in the top-right corner of the browser. The package has been successfully installed, you can now test out these features by registering an account and have a look at the database to see new entries coming in!

Tip: to not always have to fill in data in forms, you can installFake Filler as a Chrome plugin and will fill in some dummy data.

4. Laravel controller

We are going to generate a controller. For this example we will generate aresource controller, which is common when building a CRUD application. Let's call thisAddressController as we will be working with, well, addresses. Let's also add the model Address.

You will get the messageA App\Models\Address model does not exist. Do you want to generate it? (yes/no) [yes]:, just type yes and hit enter.

phpartisanmake:controllerAddressController--resource--model=Address
Enter fullscreen modeExit fullscreen mode

Screenshot 2021-04-08 at 14.02.23

5. Blade pages

Let's make our blade pages. For now, we will just make 2 different pages:index andcreate. First one will be the page where we will show the given address, the other page will be the form page.

Copy the code from thedashboard.blade.php page and edit. Add a small link to thecreate.blade.php page and paste some code there as well.

Yourindex.blade.php should look something like this:
Screenshot 2021-04-08 at 14.18.58

The file structure should be like this:
Screenshot_2021-04-08_at_14.19.44

6. Routes

Now we want to be able to navigate to our address pages.

We have to do these things:

  • Create a route to Address
  • Add the view to our AddressController
  • Add the link in the navigation bar

First things first. Navigate toweb.php and you will see a route to the dashboard. We want the dashboard and address pages to be accessible when logged in.

So we are going to group these like this - and don't forget to adduse App\Http\Controllers\AddressController; at the top of the page:

Route::group(['middleware'=>'auth'],function(){Route::get('/dashboard',function(){returnview('dashboard');})->name('dashboard');Route::resource('address',AddressController::class);});
Enter fullscreen modeExit fullscreen mode

Next, openAddressController.php. In theindex function addreturn view(address.index). We are telling the router to show theindex.blade.php when navigating to /address.

Last step is editing thenavigation.blade.php, which can be found under /views/layouts (or by searching with ⌘ + P on a Mac, Ctrl + P on a Windows machine). Copy the Dashboard part under<!-- Navigation Links —> and edit like this:

<!-- Navigation Links --><divclass="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex"><x-nav-link:href="route('dashboard')":active="request()->routeIs('dashboard')">        {{ __('Dashboard') }}</x-nav-link></div><divclass="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex"><x-nav-link:href="route('address.index')":active="request()->routeIs('address.index')">        {{ __('Address') }}</x-nav-link></div>
Enter fullscreen modeExit fullscreen mode

Refresh your page and you will see the Address-section in the navigation bar, and you will be open the index page. If you click on the part where you can add details, you will get an empty page. That brings us to the next step...

7. Google entered then room

We are going to use Google's autocomplete form and copy all the code. You will have to make a developers account, generate an API key and put it in your.env file so it'snever shared or uploaded to GitHub.

First, let's generate an API key. Navigate to theGoogle Cloud Platform after you logged in and click on APIs & Services → Credentials. Create a project, preferably with the same name as your repo. When the page is loaded, click on+ CREATE CREDENTIALS-> API KEY. Your generated API KEY will be in front of you. Congrats!
Screenshot 2021-04-08 at 14.56.40

Copy the key and paste it in your.env file of your project, and name it something like GOOGLE_KEY. Save, and restart yourphp artisan serve command.

The key is is not yet assigned to the libraries we are using. Head to the library section in the left hand side and search for 'Maps JavaScript API' and 'Places API'. Click both on enable.

You will have to enable billing on the project, more on this later on.

8. Importing the form

Let's open thecreate.blade.php of our address section. Copy all the code fromindex.blade.php of the Address section. Delete the text we wrote before.

Now, go to theGoogle Developers page of Place Autocomplete Address Form. Head over to the code, click on All, and copy the codestarting from<style type="text/css"> until></script>. Paste this in between the<x-app-layout> tags we copied earlier.

Import your GOOGLE_KEY from.env file, like this:
Screenshot 2021-04-08 at 15.47.17

Refresh your page, and with some luck you will be seeing something like this:
Screenshot 2021-04-08 at 15.50.10

9. Google billing

Open the console of your browser. Try typing something in the first input. You will see an error in your console, regarding billing. Google asks you toenable billing when using some of their API's. Not to worry though, you get sufficientfree credit and you won't be billed if the trial ends. Be sure to check it now and then though, avoiding any surprises. It's up to you if you want so link your credit card to this, but I believe that it's totally worth it when it's for your own educational purposes.

So after this, go back to the project, refresh the page and type something in the form. You will now see the autocomplete works! For now the autocomplete is limited to USA and Canada, but it's possible to change those in the code (see belowcomponentRestrictions: { country: ["us", "ca"] }).

Screenshot 2021-04-08 at 16.16.24

Screenshot 2021-04-08 at 16.17.45

10. Back-end part

Here's where the magic happens ✨.

First, let's create amigration.

phpartisanmake:migrationcreate_addresses_table
Enter fullscreen modeExit fullscreen mode

A migration file wil be added to /database/migrations. Open the file and we will add the values we get from the Google autocomplete form.

As we see from our form (using thename values), the values ofship_address, address2, locality, state, postcode, country will be written to the database. Changeship-address toship_address in the form under the name attribute.

Let's also adduser_id as we will store and load the address of every unique user who registers.

Add->nullable() toaddress2 as we won't always have to fill in an apartment or floor number. This function will automatically add 'Allow null' to this row when we migrate.

Screenshot 2021-04-09 at 12.10.31

Open up theAddress model. Fill in the all the same values.

Screenshot 2021-04-09 at 12.10.57

Finish off withphp artisan migrate. As you can see, the table is migrated to our database.

Screenshot 2021-04-09 at 14.17.41

11. Form behaviour

Open up the form again (create.blade.php from Address). Each form requires an action. We are going to use the store-function to write the data to our database. Add the route[address.store](http://address.store) to the action attribute and change to the method topost. Also add@csrf below this line.

<formmethod="post"action="{{ route('address.store') }}"autocomplete="off"id="google-map">    @csrf
Enter fullscreen modeExit fullscreen mode

Let's add a success message to our form, with some simpleTailwind styling.

@if(Session::has('success'))<divclass="text-green-700 bg-green-100"role="alert">{{Session::get('success')}}</div>@endif
Enter fullscreen modeExit fullscreen mode

12. Store function

Last step. Open up theAddressController where you will find the store() function, filled in withRequest $request as variable. We can just use the data we get from the $request to write to the database. But there's just one variable we have to get somewhere else. Theuser_id is a value we won't get from the form, but it's stored asAuth::id() when we're logged in.

publicfunctionstore(Request$request){$data=$request->input();$data['user_id']=Auth::id();Address::create($data);returnback()->with('success',"Info updated successfully.");}
Enter fullscreen modeExit fullscreen mode

We return with a simple success message.

Open up your browser and put in some data and see how it's been written in the database.

13. Showing the address (when previously created)

We want to greet the user when logged in with previously stored address, when provided.

Open up theindex.blade.php and add following code. This part will only be loaded when there is already an address stored for this particular id.

@if(!empty($address))<divclass="pt-12"><divclass="max-w-7xl mx-auto sm:px-6 lg:px-8"><divclass="bg-white overflow-hidden shadow-sm sm:rounded-lg"><divclass=" p-6 bg-white border-b border-gray-200">Youraddressis:<ulclass="list-inside"><li>Street+number:{{$address->ship_address}}</li>@if(!empty($address->address2))<li>Apartment,unit,suite,orfloor:{{$address->address2}}</li>@endif<li>City:{{$address->locality}}</li><li>Country:{{$address->country}}</li></ul></div></div></div></div>@endif
Enter fullscreen modeExit fullscreen mode

We need a function that gets the data from the database. Open up theAddressController. We're going to rewrite theindex() function. The$address variable will grab the latest entry in the database with a certain id, the one that is used to log in.

publicfunctionindex(){$address=DB::table('addresses')->where('user_id',Auth::user()->id)->latest('updated_at')->first();returnview('address.index',compact('address'));}
Enter fullscreen modeExit fullscreen mode

We return theaddress.index view with the $address variable, we can write it ascompact('address').

Don't forget to adduse Illuminate\Support\Facades\DB; at the top.

That's it! A basic Laravel 8 example with a Google Autocomplete form.

I also put the the code in this GitHubrepo.

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
jhanleycom profile image
John J. Hanley
  • Joined

Some parts of your code/html are pictures. One is too small to even read. Please replace with content that can be copied/pasted like the other sections of your article.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Started coding not so long ago. Now a full stack developer with strong interest in everything web dev.Coffee, music and 26-inch bike enthousiast.
  • Location
    Ghent, Belgium
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp