Laravel Select2 Ajax Autocomplete Example

Hi Dev,

Nowadays, I will create auto whole the use of Select2 and Ajax in laravel. we are able to show automobile whole the use of select2.js in laravel. you can easyli create auto whole the usage of select2 and ajax in laravel.

I will give you full example of select2 ajax in laravel.

Step 1 : Install Laravel 7 Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog
Database Configuration

In this step, we require to make database configuration, you have to add following details on your .env file.

1.Database Username

2.Database Password

3.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:

.env
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Step 2: Create product Table and Model

In this step we have to create migration for product table using Laravel 6 php artisan command, so first fire bellow command:

php artisan make:model Product -m

After this command you have to put bellow code in your migration file for create product table.

/database/migrations/2020_03_05_100722_create_product_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('price');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}
Now we require to run migration be bellow command:
php artisan migrate
After you have to put bellow code in your model file for create product table. /app/Product.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
     protected $fillable = [
        'name', 'price',
    ];
}
Step 3: Create Route

now, we need to add resource route for select2 crud operations in laravel application. so open your "routes/web.php" file and add following route.

/routes/web.php
Route::get('select2', 'Select2AutocompleteController@index');
Route::get('/select2-autocomplete-ajax', 'Select2AutocompleteController@dataAjax');
Step 4: Create Controller

here this step now we should create new controller as Select2AutocompleteController. So run bellow command and create new controller.

php artisan make:controller Select2AutocompleteController

In this controller will create two methods by default as bellow methods:

1)index()

2)dataAjax()

So, let's copy bellow code and put on ItemController.php file.

/app/Http/Controllers/Select2AutocompleteController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;

class Select2AutocompleteController extends Controller
{
    /**
    * Show the application layout.
    *
    * @return \Illuminate\Http\Response
    */
    public function index()
    {
    	return view('select2.index');
    }
    
    /**
    * Show the application dataAjax.
    *
    * @return \Illuminate\Http\Response
    */
    public function dataAjax(Request $request)
    {
    	$data = [];

        if($request->has('q')){
            $search = $request->q;
            $data =Product::select("id","name")
            		->where('name','LIKE',"%$search%")
            		->get();
        }
        return response()->json($data);
    }
}
Step 5:Create View

In last step. In this step we have to create just blade files. So mainly we have to create layout file and then create new folder "select2" then create blade files of crud app. So finally you have to create following bellow blade file:

here create following file and put bellow code.

/resources/views/select2/index.blade.php
<!DOCTYPE html>
<html>
<head>
  <title>Laravel - Dynamic autocomplete search using select2 JS Ajax</title>
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body class="bg-dark">
<div class="container mt-4">
  <div class="row">
    <div class="col-md-8 offset-md-2">
      <div class="card">
        <div class="card-header">
          <h4>Laravel - Dynamic autocomplete search using select2 JS Ajax</h4>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-12">
              <select class="itemName form-control" name="itemName"></select>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
<script type="text/javascript">
$('.itemName').select2({
  placeholder: 'Select an item',
  ajax: {
    url: '/select2-autocomplete-ajax',
    dataType: 'json',
    delay: 250,
    processResults: function (data) {
      return {
        results:  $.map(data, function (item) {
              return {
                  text: item.name,
                  id: item.id
              }
          })
      };
    },
    cache: true
  }
});
</script>
</html>
Now we are ready to run our example so run bellow command for quick run:
php artisan serve
Now you can open bellow URL on your browser:
http://localhost:8000/select2

It will help you...

Laravel 8 Socialite Login with Google Gmail Account

Laravel 8 Socialite Login with Google Gmail Account

Hello Dev,

Today, I can provide an explanation for you grade by grade login with google account in laravel 8 using socialite. laravel 8 socialite offer api to login with gmail account. you could without difficulty login the usage of google account in laravel 8 utility.

As we understand social media is a end up more and more famous within the global. each one have social account like gmail, facebook and so forth. i think additionally maximum of have gmail account. So if to your application have login with social then it come to be first-rate. you bought more people hook up with your internet site because maximum of people does no longer want to fill join up or register shape. If there login with social than it turn out to be remarkable.

So if you want to also implement login with google gmail account then i will help you step by step instruction. let's follow tutorial and implement it.

Step 1 : Install Laravel 8

In the first step, we need to get fresh laravel 8 version application So let's open terminal and run bellow command to install fresh laravel project.

composer create-project --prefer-dist laravel/laravel blog
Step 2 : Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3 : Install Jetstream

Here we need auth scaffolding of jetstream. i will give full example for how to install jetstream so click here.

Step 4 : Install Socialite

In this step, we need laravel/socialite package. you can install socialite package using bellow command so let's run bellow command :

composer require laravel/socialite

After install above package you can add providers and aliases in config file, Now open config/app.php file and add service provider and aliase.

config/app.php
....

'providers' => [
    ....
    Laravel\Socialite\SocialiteServiceProvider::class,
],

'aliases' => [
    ....
    'Socialite' => Laravel\Socialite\Facades\Socialite::class,
],

....
Step 5: Create Google App

Here we need google client id and secret that way we can get information of other user. so if you don't have google app account then you can create from here : Google Developers Console. you can find bellow screen :

Laravel 8 Socialite Login with Google Gmail Account

Now you have to click on Credentials and choose first option oAuth and click Create new Client ID button. now you can see following slide:

Laravel 8 Socialite Login with Google Gmail Account
Laravel 8 Socialite Login with Google Gmail Account

after create account you can copy client id and secret.

Now you have to set app id, secret and call back url in config file so open config/services.php and set id and secret this way:

config/services.
return [
    ....
    'google' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://localhost:8000/auth/google/callback',
    ],
]
Step 6: Add Database Column

In this step first we have to create migration for add google_id in your user table. So let's run bellow command:

php artisan make:migration add_google_id_column_in_users_table  --table=users
database/migrations/2020_09_18_052105_add_google_id_column_in_users_table.php
<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class AddGoogleIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->string('google_id')->nullable();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('google_id');
         });
    }
}

Update mode like this way:

app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Jetstream\HasProfilePhoto;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens;
    use HasFactory;
    use HasProfilePhoto;
    use Notifiable;
    use TwoFactorAuthenticatable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'google_id'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
        'two_factor_recovery_codes',
        'two_factor_secret',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = [
        'profile_photo_url',
    ];
}
Step 7: Create Routes

Here, we need to add resource route for login with gmail account. so open your "routes/web.php" file and add following route.

routes/web.php
use App\Http\Controllers\Auth\GoogleController;

Route::get('auth/google', [GoogleController::class, 'redirectToGoogle']);
Route::get('auth/google/callback', [GoogleController::class, 'handleGoogleCallback']);
Step 8: Create Controller

After add route, we need to add method of google auth that method will handle google callback url and etc, first put bellow code on your GoogleController.php file

app/Http/Controllers/Auth/GoogleController.php
<?php
  
namespace App\Http\Controllers\Auth;
  
use App\Http\Controllers\Controller;
use Socialite;
use Auth;
use Exception;
use App\Models\User;
  
class GoogleController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToGoogle()
    {
        return Socialite::driver('google')->redirect();
    }
      
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleGoogleCallback()
    {
        try {
    
            $user = Socialite::driver('google')->user();
     
            $finduser = User::where('google_id', $user->id)->first();
     
            if($finduser){
     
                Auth::login($finduser);
    
                return redirect('/dashboard');
     
            }else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'google_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
    
                Auth::login($newUser);
     
                return redirect('/dashboard');
            }
    
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}
Step 9: Update Blade File

Ok, now at last we need to add blade view so first create new file login.blade.php file and put bellow code:

resources/views/auth/login.blade.php
<x-guest-layout>
    <x-jet-authentication-card>
        <x-slot name="logo">
            <x-jet-authentication-card-logo />
        </x-slot>

        <x-jet-validation-errors class="mb-4" />

        @if (session('status'))
            <div class="mb-4 font-medium text-sm text-green-600">
                {{ session('status') }}
            </div>
        @endif

        <form method="POST" action="{{ route('login') }}">
            @csrf

            <div>
                <x-jet-label value="{{ __('Email') }}" />
                <x-jet-input class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus />
            </div>

            <div class="mt-4">
                <x-jet-label value="{{ __('Password') }}" />
                <x-jet-input class="block mt-1 w-full" type="password" name="password" required autocomplete="current-password" />
            </div>

            <div class="block mt-4">
                <label class="flex items-center">
                    <input type="checkbox" class="form-checkbox" name="remember">
                    <span class="ml-2 text-sm text-gray-600">{{ __('Remember me') }}</span>
                </label>
            </div>

            <div class="flex items-center justify-end mt-4">
                @if (Route::has('password.request'))
                    <a class="underline text-sm text-gray-600 hover:text-gray-900" href="{{ route('password.request') }}">
                        {{ __('Forgot your password?') }}
                    </a>
                @endif

                <x-jet-button class="ml-4">
                    {{ __('Login') }}
                </x-jet-button>

                    <a href="{{ url('auth/google') }}" style="margin-top: 0px !important;background: green;color: #ffffff;padding: 5px;border-radius:7px;" class="ml-2 btn-google">
                      <strong>Login With Google</strong>
                    </a> 
            </div>
        </form>
    </x-jet-authentication-card>
</x-guest-layout>

Now we are ready to run laravel 8 socialite login with Google gmail account so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

localhost:8000/login
Output
Laravel 8 Socialite Login with Google Gmail Account

It will help you...