16

I am new to Laravel however and I am following the tutorial on http://www.codeanchor.net/blog/complete-laravel-socialite-tutorial/, to login a user through Facebook into my application. However, almost everywhere I find a tutorial using either Github or Twitter for the Socialite Plugin provided in Laravel.

My problem is that on following everything in the tutorial, as I click on the "Login to Facebook" button, it throws an "Invalid Argument Exception" with No Socialite driver was specified.".

Another stack overflow question seemed to narrow things down: https://stackoverflow.com/questions/29673898/laravel-socialite-invalidargumentexception-in-socialitemanager-php-line-138-n

Stating that the problem is in the config/services.php

Now, i have the app_id and app_secret. However, the redirect link seems to be confusing as I can't find it on Facebook either. I am aware that this is where my app should go to Facebook for login, however, unsure of what it should be.

Does anyone have any idea on this.

4 Answers 4

39

In your composer.json add- "laravel/socialite": "~2.0",

"require": {
        "laravel/framework": "5.0.*",
        "laravel/socialite": "~2.0",

the run composer update

In config/services.php add:

//Socialite
    'facebook' => [
        'client_id'     => '1234567890444',
        'client_secret' => '1aa2af333336fffvvvffffvff',
        'redirect'      => 'http://laravel.dev/login/callback/facebook',
    ],

You need to create two routes, mine are like these:

//Social Login
Route::get('/login/{provider?}',[
    'uses' => 'AuthController@getSocialAuth',
    'as'   => 'auth.getSocialAuth'
]);


Route::get('/login/callback/{provider?}',[
    'uses' => 'AuthController@getSocialAuthCallback',
    'as'   => 'auth.getSocialAuthCallback'
]);

You also need to create controller for the routes above like so:

<?php namespace App\Http\Controllers;

 use Laravel\Socialite\Contracts\Factory as Socialite;

 class AuthController extends Controller
 {

       public function __construct(Socialite $socialite){
           $this->socialite = $socialite;
       }


       public function getSocialAuth($provider=null)
       {
           if(!config("services.$provider")) abort('404'); //just to handle providers that doesn't exist

           return $this->socialite->with($provider)->redirect();
       }


       public function getSocialAuthCallback($provider=null)
       {
          if($user = $this->socialite->with($provider)->user()){
             dd($user);
          }else{
             return 'something went wrong';
          }
       }

 }

and finally add Site URL to your Facebook App like so:

enter image description here

5
  • how to create facebook as provider to get the client_id and cilent_secret?
    – yudijohn
    Dec 11, 2015 at 2:49
  • 1
    @yudijohn, regard to your question, you should create an application in Facebook. Anyway, that's something you should post as a new question.
    – whoan
    Dec 24, 2015 at 13:31
  • Can you explain what the second route does if you already have a redirect in the config/services? Mar 3, 2016 at 3:43
  • For that redirect in your services to work you must create a route that will be called. After authentication on Facebook it redirects to callback URL so if the route doesn't exist you will get not found error
    – Emeka Mbah
    Mar 3, 2016 at 4:11
  • An easy way to register app is here- youtube.com/watch?v=HIf0JW7JhcE Aug 27, 2016 at 16:56
3

Update 2018 - laravel 5.6 - socialite 3.0

It's little bit tricky for something that looks/should be easy, but anyway this is how i make things works for me.

Server side

you can find those instructions and more details in socialite docs

Installation

composer require laravel/socialite

Configuration

in config/services.php add

'facebook' => [

    'client_id'     => env('FACEBOOK_CLIENT_ID'),
    'client_secret' => env('FACEBOOK_CLIENT_SECRET'),
    'redirect'      => env('FACEBOOK_CALLBACK_URL'),
],

in .env file add

FACEBOOK_CLIENT_ID=paste_client_id_here
FACEBOOK_CLIENT_SECRET=paste_client_secret_here
FACEBOOK_CALLBACK_URL=https://www.example.com/auth/facebook/callback

in routes/web.php add

Route::get('auth/facebook/', 'Auth\FacebookController@redirect')->name('auth.facebook');

Route::get('auth/facebook/callback', 'Auth\FacebookController@callback')->name('auth.facebook.callback');

in App\Http\Controllers\Auth add new controller FacebookController.php

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Socialite;

class FacebookController extends Controller {

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirect()
    {
        return Socialite::driver('facebook')->redirect();
    }


    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function callback(Request $request)
    {
        try {

            $facebookAccount = Socialite::driver('facebook')->user();

            // your logic here...

            return redirect()->route('your.route.name');


        } catch (Exception $e) {


            return redirect()->route('auth.facebook');
        }
    }
}

Facebook side

go to https://developers.facebook.com/apps and create new app (if you don't have one already)

and make sur your app settings are like below in those screen shots:

enter image description here

enter image description here

Important note

If you are developing in your local machine, you have to use tools like ngrok that provide a secure link to your localhost.

In the facebook login settings change https://www.example.com with the url provided by ngrok something like https://8b0215bc.ngrok.io.

It is the only way that worked for me while developing in my local machine.

0

Create a provider under your config/services.php file

'facebook' => [
    'client_id' => 'your-fb-client-id',
    'client_secret' => 'your-fb-secret',
    'redirect' => 'http://your-redirect.com/route',
],

now you can create a controller with following code

//this function will redirect users to facebook login page
public function facebook()
{
    return \Socialize::with('facebook')->redirect();
}

public function callback()
{
    $user = \Socialize::with('facebook')->user();

    //now we have user details in the $user array
     dd($user);

}

and this is your route

Route::get('facebook', 'LoginController@facebook');

Route::get('callback', 'LoginController@callback');
1
  • how to create facebook as provider to get the client_id and cilent_secret?
    – yudijohn
    Dec 11, 2015 at 2:49
0

Step 1: Install latest version of Laravel, using below command:

composer create-project --prefer-dist laravel/laravel facebookLogin

Step 2: Install Socialite

composer require laravel/socialite

Step 3: Create Facebook app

You have to go https://developers.facebook.com and create app for facebook login client id and secret key. Once you create account make sure you copy client id and secret key.

Now you have to set app id, secret and call back url in config file in your laravel code:

config/services.php

return [
    ....
    'facebook' => [
        'client_id' => 'app id',
        'client_secret' => 'add secret',
        'redirect' => 'http://localhost:8000/auth/facebook/callback',
    ],
]

There can be multiple configs added in the services file like facebook, github, twitter etc.

Step 4: Add Database Column

php artisan make:migration add_facebookId_column_users_table

<?php
  
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
   
class AddFacebookIdColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        Schema::table('users', function ($table) {
            $table->string('facebook_id')->nullable();
        });
    }
   
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        // rollback code
    }
}

Step 5: Update User Model:

namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
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',
        'facebook_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 6: Setup Routes in app/Http/routes.php

use Illuminate\Support\Facades\Route;
 use App\Http\Controllers\FacebookController;
          
 Route::get('auth/facebook', [FacebookController::class, 'redirectToFacebook']);
        Route::get('auth/facebook/callback', [FacebookController::class, 'handleFacebookCallback']);

Step 7: Add Facebook Controller app/Http/Controllers/FacebookController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Exception;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
    
class FacebookController extends Controller {
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function redirectToFacebook() {
        return Socialite::driver('facebook')->redirect();
    }
          
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function handleFacebookCallback() {
        try {
            $user = Socialite::driver('facebook')->user();
            $finduser = User::where('facebook_id', $user->id)->first();
            if($finduser) {
                Auth::login($finduser);
                return redirect()->intended('dashboard');
         
            } else{
                $newUser = User::create([
                    'name' => $user->name,
                    'email' => $user->email,
                    'facebook_id'=> $user->id,
                    'password' => encrypt('123456dummy')
                ]);
        
                Auth::login($newUser);
        
                return redirect()->intended('dashboard');
            }
        
        } catch (Exception $e) {
            dd($e->getMessage());
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.