Laravel is one of the most popular PHP frameworks that makes building web applications easier and faster. It comes with a variety of built-in features, such as authentication and security, making it a popular choice for developers worldwide. One of the most commonly used authentication methods is social login, where users can log in to your application using their social media accounts. In this article, we will show you how to implement Facebook login in Laravel 9.
Step 1: Create a New Laravel Project
First, create a new Laravel project by running the following command in your terminal:
composer create-project --prefer-dist laravel/laravel facebook-login
This command will create a new Laravel project called facebook-login
.
Step 2: Set Up the Facebook App
Before you can use Facebook login in your Laravel application, you need to create a Facebook app. To do this, go to the Facebook Developer Console and click on the “Create App” button. Then follow the on-screen instructions to create your app.
Once your app is created, you will be redirected to the App Dashboard. From here, click on the “Add Product” button and select “Facebook Login” from the list.
Next, click on the “Settings” tab and enter your application’s URL in the “Valid OAuth Redirect URIs” field. This is the URL that Facebook will redirect the user to after they have logged in.
Finally, click on the “Save Changes” button to save your settings.
Step 3: Install the Facebook SDK
To use Facebook login in Laravel, you need to install the Facebook SDK. You can do this by running the following command in your terminal:
composer require facebook/graph-sdk
This command will install the Facebook SDK in your Laravel project.
Step 4: Create the Facebook Login Button
Next, create a Facebook login button on your login page. You can use the following code to create a Facebook login button:
<a href="{{ url('login/facebook') }}" class="btn btn-primary">Login with Facebook</a>
This code creates a button that will redirect the user to the URL /login/facebook
when clicked.
Step 5: Create the Facebook Login Route
In Laravel, you need to create a route that will handle the Facebook login request. You can create this route by adding the following code to your routes/web.php
file:
Route::get('login/facebook', 'Auth\LoginController@facebookLogin');
This code creates a route that will call the facebookLogin
method in the LoginController
class when the user clicks on the Facebook login button.
Step 6: Create the Facebook Login Method
In the LoginController
class, create a new method called facebookLogin
that will handle the Facebook login request. You can use the following code to create this method:
public function facebookLogin(){ $fb = new \Facebook\Facebook([ 'app_id' => env('FACEBOOK_APP_ID'), 'app_secret' => env('FACEBOOK_APP_SECRET'), 'default_graph_version' => 'v11.0', ]); $helper = $fb->getRedirectLoginHelper(); $permissions = ['email']; // Optional permissions $loginUrl = $helper->getLoginUrl(url('login/facebook/callback'), $permissions); return redirect()->to($loginUrl);}
This code creates a new instance of the Facebook SDK and uses the getRedirectLoginHelper
method to generate a Facebook login URL. The url
method is used to generate the callback URL, which will be called by Facebook after the user has logged in. The redirect
method is used to redirect the user to the Facebook login page.
Step 7: Create the Facebook Login Callback Method
After the user logs in to Facebook, they will be redirected to the callback URL that you specified in the previous step. In the LoginController
class, create a new method called facebookCallback
that will handle the callback request. You can use the following code to create this method:
public function facebookCallback(){ $fb = new \Facebook\Facebook([ 'app_id' => env('FACEBOOK_APP_ID'), 'app_secret' => env('FACEBOOK_APP_SECRET'), 'default_graph_version' => 'v11.0', ]); $helper = $fb->getRedirectLoginHelper(); try { $accessToken = $helper->getAccessToken(); } catch (\Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error echo 'Graph returned an error: ' . $e->getMessage(); exit; } catch (\Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } if (!isset($accessToken)) { if ($helper->getError()) { header('HTTP/1.0 401 Unauthorized'); echo "Error: " . $helper->getError() . "\n"; echo "Error Code: " . $helper->getErrorCode() . "\n"; echo "Error Reason: " . $helper->getErrorReason() . "\n"; echo "Error Description: " . $helper->getErrorDescription() . "\n"; } else { header('HTTP/1.0 400 Bad Request'); echo 'Bad request'; } exit; } // Logged in $fb->setDefaultAccessToken($accessToken); try { $response = $fb->get('/me?fields=id,name,email'); $userNode = $response->getGraphUser(); } catch (\Facebook\Exceptions\FacebookResponseException $e) { // When Graph returns an error echo 'Graph returned an error: ' . $e->getMessage(); exit; } catch (\Facebook\Exceptions\FacebookSDKException $e) { // When validation fails or other local issues echo 'Facebook SDK returned an error: ' . $e->getMessage(); exit; } // Store user information in the database $user = User::where('email', $userNode->getEmail())->first(); if (!$user) { $user = new User(); $user->name = $userNode->getName(); $user->email = $userNode->getEmail(); $user->password = bcrypt(str_random(10)); $user->save(); } // Log the user in Auth::login($user); return redirect()->to('/home');}
This code gets the access token from Facebook and uses it to get the user’s information, such as their name and email address. It then stores this information in the database and logs the user in using Laravel’s built-in authentication system.
Step 8: Add Facebook App Credentials to .env File
In order to use the Facebook SDK, you need to provide your Facebook app credentials. Open the .env
file in your Laravel project and add the following lines:
FACEBOOK_APP_ID=your_app_id_hereFACEBOOK_APP_SECRET=your_app_secret_here
Replace your_app_id_here
and your_app_secret_here
with your Facebook app’s ID and secret key.
Step 9: Test the Facebook Login
Now you can test the Facebook login by clicking on the “Login with Facebook” button on your login page. If everything is set up correctly, you should be redirected to Facebook to log in and then redirected back to your Laravel application. If the login is successful, you should be redirected to the /home
page.
Conclusion
In this article, we have gone through the steps to set up Facebook login in a Laravel 9 application. We started by creating a new Facebook app and configuring it with the necessary settings. Then we installed the Facebook PHP SDK using Composer and added the necessary routes and controllers to handle the login flow. Finally, we tested the login and saw that it worked as expected.
Adding social login to your Laravel application can make it more user-friendly and help you attract more users. By using Facebook login, you can simplify the registration and login process for your users, as they won’t have to remember yet another username and password. Plus, you can get access to their social graph data, which can help you personalize their experience on your site. With the steps outlined in this article, you should now be able to implement Facebook login in your own Laravel 9 application.
Comments
Post a Comment