This tutorial will guide you through the process of adding Facebook login functionality to your Laravel application.
Laravel Socialite provides an expressive, fluent interface to OAuth authentication with Facebook, Twitter, Google, LinkedIn, GitHub, GitLab and Bitbucket.
Install it via Composer:
composer require laravel/socialite
Add the following to your config/services.php file:
'facebook' => [ 'client_id' => env('FACEBOOK_CLIENT_ID'), 'client_secret' => env('FACEBOOK_CLIENT_SECRET'), 'redirect' => env('FACEBOOK_REDIRECT_URI'), ],
Then, add these to your .env file:
FACEBOOK_CLIENT_ID=your_facebook_app_id FACEBOOK_CLIENT_SECRET=your_facebook_app_secret FACEBOOK_REDIRECT_URI=http://localhost:8000/login/facebook/callback
Add these routes to your routes/web.php:
use App\Http\Controllers\Auth\FacebookController; Route::get('login/facebook', [FacebookController::class, 'redirectToFacebook'])->name('login.facebook'); Route::get('login/facebook/callback', [FacebookController::class, 'handleFacebookCallback']);
Create a new controller:
php artisan make:controller Auth/FacebookController
Implement the controller:
redirect(); } 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()); } } }
Add facebook_id to the fillable array in your User model:
protected $fillable = [ 'name', 'email', 'password', 'facebook_id', ];
Create a new migration:
php artisan make:migration add_facebook_id_to_users_table
In the new migration file:
public function up() { Schema::table('users', function ($table) { $table->string('facebook_id')->nullable(); }); } public function down() { Schema::table('users', function ($table) { $table->dropColumn('facebook_id'); }); }
Run the migration:
php artisan migrate
In your login view, add a "Login with Facebook" button:
Login with Facebook
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3