LARAVEL Tutorial


Laravel 7 Socialite Facebook Login Example


Laravel socialite facebook login example. Here you will learn how to implement social login in laravel web applications.

We will explain how to add social Facebook login button to your laravel web applications and simple authentication (login) to users using login button in your web app. 

Laravel Socialite Facebook Login Example

  • Install Laravel Application
  • Configure Database Detail
  • Install Laravel Socialite Package
  • Get Secret id & key From Facebook 
  • Run Migration
  • Create Routes
  • Generate Controller By Artisan
  • Create Blade View
  • Start Development Server

Install Laravel Application

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

composer create-project laravel/laravel laravel-social-login –-prefer-dist

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=root

Install Laravel Socialite Package

Use the following command to install or download laravel socialite package. So open your command prompt run the following command: 

composer require laravel/socialite

After that, we need to configure the aliases and provider in config/app.php.

'providers' => [

    // Other service providers…

    Laravel\Socialite\SocialiteServiceProvider::class,

 ],

'aliases' => [

   // Other aliases…

   'Socialite' => Laravel\Socialite\Facades\Socialite::class,

 ], 

Get Secret id & key From Facebook 

Now, We need to required the CLIENT ID and CLIENT SECRET to add social facebook login button in the laravel web applications. Lets go to https://developers.facebook.com/apps/ and create a new app.

After that, Set client id and client secret config/service.php file.

'facebook' => [
     'client_id' => 'xxxx',
     'client_secret' => 'xxx',
     'redirect' => 'https://www.w3alert.com/laravel-social-login/callback/facebook',
   ], 

Next, go to app/User.php and set fillable property. Looks like below:

protected $fillable = [ 'name', 'email', 'password', 'provider', 'provider_id' ];

Next step, Go to app/database/create_users_table.php and put the below code here :
 

<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('provider');
            $table->string('provider_id');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Run Migration

Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :

..
use Illuminate\Support\Facades\Schema;
 
....
function boot()
{
    Schema::defaultStringLength(191);
}
... 

Next, go to command prompt and run the following command:

php artisan migrate

OR

php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

Route::get('facebook', 'SocialiteController@index');
Route::get('/auth/{provider}', 'SocialiteController@redirect');
Route::get('/callback/{provider}', 'SocialiteController@callback');

Generate Controller By Artisan

Now, you need to generate or create a controller file using php artisan command, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller SocialiteController

After that, go to App/Http/Controllers/ directory and find the created SocialiteController file and update the following code into your file:

<?php

 namespace App\Http\Controllers;
 use Illuminate\Http\Request;
 use Validator,Redirect,Response,File;
 use Socialite;
 use App\User;

 class SocialiteController extends Controller
 {

 public index()
 {
     return view('login');
 }
 
 public function redirect($provider)
 {
     return Socialite::driver($provider)->redirect();
 }

 public function callback($provider)
 {
   $getInfo = Socialite::driver($provider)->user(); 
   $user = $this->create($getInfo,$provider); 
   auth()->login($user); 
   return redirect()->to('/home');
 }

 function create($getInfo,$provider)
 {

   $user = User::where('provider_id', $getInfo->id)->first();
   if (!$user) {
        $user = User::create([
           'name'     => $getInfo->name,
           'email'    => $getInfo->email,
           'provider' => $provider,
           'provider_id' => $getInfo->id
       ]);
     }
     return $user;
  }

}

Create Blade Views

Next, you need to create a blade views file, so go resource/views directory and create the following blade views file.

Go to resource/views/ then create a new file name login.blade.php and update the following code:

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="csrf-token" content="{{ csrf_token() }}">

  <title>Laravel Socialite Facebook Login - w3alert.com</title>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

  <style>
   .error{ color:red; } 
  </style>

</head>
 
<body>
 
<div class="container mt-5">

  <div class="form-group row mb-0">
   <div class="col-md-8 offset-md-4">
      <a href="{{ url('/auth/redirect/facebook') }}" class="btn btn-primary"><i class="fa fa-facebook"></i> Facebook</a>
  </div>
  </div>
</div>
</body>
</html>

Go to resource/views and create a new file name home.blade.php. Then update the below code into your file:

<!doctype html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="csrf-token" content="{{ csrf_token() }}">

  <title>Laravel Socialite Facebook Login - w3alert.com</title>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />

  <style>
   .error{ color:red; } 
  </style>

</head>
 
<body>
 <div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Dashboard</div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif    
                 @if(Auth::user()->avatar)
                 <img src="{{ Auth::user()->avatar }}" class="rounded" alt="hello" width="208px">
                 @else
                 <img src="{{ asset('public/images/no-image.png') }}" class="rounded" alt="hello" width="208px">
                 @endif              
                 <h2 class="mt-3">Welcome - {{ ucwords(Auth::user()->name) }}</h2>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your browser and type the below-given URL into your browser:

http://localhost:8000/facebook

OR

http://localhost/laravel-social-login/public/facebook