Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

LaravelFacebookSdk

> 编程语言
Open source

Fully unit tested Facebook SDK v5 integration for Laravel & Lumen

689 stars0 likes1 views
WebsiteGitHub

About

Fully unit tested Facebook SDK v5 integration for Laravel & Lumen

Laravel Facebook SDK

A fully unit-tested package for easily integrating the Facebook SDK v5 into Laravel and Lumen 5.0, 5.1, 5.2, & 5.3.


This is package for Laravel and Lumen 5.0, 5.1, 5.2, & 5.3

  • For Laravel 4.2, see the 1.3 branch.

  • Installation
  • User Login From Redirect Example
  • Making Requests To Facebook
  • Facebook Login
  • Saving Data From Facebook In The Database
  • Logging The User Into Laravel
  • Working With Multiple Apps
  • Error Handling
  • Troubleshooting
  • Testing
  • Contributing
  • Credits
  • License

Shouldn't I just use Laravel Socialite?

Laravel 5 comes with support for Socialite which allows you to authenticate with OAuth 2.0 providers. Facebook Login uses OAuth 2.0 and therefore Socialite supports Facebook Login.

If all you need is to authenticate an app and grab a user access token to pull basic data on a user, then Socialite or The PHP League's Facebook OAuth Client should suffice for your needs.

But if you need any of the following features, you'll want to tie in the Facebook PHP SDK with this package:

  • Obtaining an access token from the signed request in:
    • The cookie set by the Facebook JavaScript SDK
    • The signed_request param POST'ed to an app canvas
    • The signed_request param POST'ed to a Facebook page tab
  • Photo or video uploads
  • Batch requests
  • Easy pagination
  • Getting Graph data returned as collections

Installation

Add the Laravel Facebook SDK package to your composer.json file.

composer require sammyk/laravel-facebook-sdk

Auto-discovery: As of version 3.5.0, the Laravel Facebook SDK supports auto-discovery for Laravel 5.5 and greater.

Service Provider

In your app config, add the LaravelFacebookSdkServiceProvider to the providers array.

php
'providers' => [
    SammyK\LaravelFacebookSdk\LaravelFacebookSdkServiceProvider::class,
    ];

For Lumen, add the provider to your bootstrap/app.php file.

php
$app->register(SammyK\LaravelFacebookSdk\LaravelFacebookSdkServiceProvider::class);

Facade (optional)

If you want to make use of the facade, add it to the aliases array in your app config.

php
'aliases' => [
    'Facebook' => SammyK\LaravelFacebookSdk\FacebookFacade::class,
    ];

But there are much better ways to use this package that don't use facades.

IoC container

The IoC container will automatically resolve the LaravelFacebookSdk dependencies for you. You can grab an instance of LaravelFacebookSdk from the IoC container in a number of ways.

…

Configuration File

Note: As of version 3.4.0, publishing the config file is optional as long as you set your required config values.

Also note: The config file contains a default Graph API version that gets bumped up to the latest stable version periodically which might cause a breaking change when you update this package in a minor or patch version. It is recommended that you still publish the config file and update the Graph API version on your own time to prevent breaking things.

After creating an app in Facebook, you'll need to provide the app ID and secret. In Laravel you can publish the configuration file with artisan.

bash
$ php artisan vendor:publish --provider="SammyK\LaravelFacebookSdk\LaravelFacebookSdkServiceProvider" --tag="config"

Where's the file? Laravel 5 will publish the config file to /config/laravel-facebook-sdk.php.

In Lumen you'll need to manually copy the config file from /src/config/laravel-facebook-sdk.php to your config folder in your base project directory. Lumen doesn't have a /config folder by default so you'll need to create it if you haven't already.

Required config values

You'll need to update the app_id and app_secret values in the config file with your app ID and secret.

By default the configuration file will look to environment variables for your app ID and secret. It is recommended that you use environment variables to store this info in order to protect your app secret from attackers. Make sure to update your /.env file with your app ID & secret.

FACEBOOK_APP_ID=1234567890
FACEBOOK_APP_SECRET=SomeFooAppSecret

User Login From Redirect Example

Here's a full example of how you might log a user into your app using the redirect method.

This example also demonstrates how to exchange a short-lived access token with a long-lived access token and save the user to your users table if the entry doesn't exist.

Finally it will log the user in using Laravel's built-in user authentication.

Sessions in Lumen: The "login from redirect" functionality relies on sessions to store a CSRF token. Since sessions don't exist in Lumen 5.2+, you'll need to obtain an access token using a different method. For testing you can just grab an access token from the Graph API Explorer (make sure to select your app from the "Application" drop down).

…

For more details on the ways to authenticate a user, see Facebook Login.

Making Requests To Facebook

Requests to Facebook are made via the Graph API. This package is a Laravel wrapper for the official Facebook PHP SDK v5 so all the methods available to the official SDK are also available in this package.

Get User Info

The following snippet will retrieve a User node representing the logged in user.

php
try {
  $response = $fb->get('/me?fields=id,name,email', 'user-access-token');
} catch(\Facebook\Exceptions\FacebookSDKException $e) {
  dd($e->getMessage());
}

$userNode = $response->getGraphUser();
printf('Hello, %s!', $userNode->getName());

See more about the get() method.

Facebook Login

When we say "log in with Facebook", we really mean "obtain a user access token to make calls to the Graph API on behalf of the user." This is done through Facebook via OAuth 2.0. There are a number of ways to log a user in with Facebook using what the Facbeook PHP SDK calls "helpers".

The four supported login methods are:

  1. Login From Redirect (OAuth 2.0)
  2. Login From JavaScript (with JS SDK cookie)
  3. Login From App Canvas (with signed request)
  4. Login From Page Tab (with signed request)

Login From Redirect

One of the most common ways to log a user into your app is by using a redirect URL.

The idea is that you generate a unique URL that the user clicks on. Once the user clicks the link they will be redirected to Facebook asking them to grant any permissions your app is requesting. Once the user responds, Facebook will redirect the user back to a callback URL that you specify with either a successful response or an error response.

The redirect helper can be obtained using the SDK's getRedirectLoginHelper() method.

Generating a login URL

You can get a login URL just like you you do with the Facebook PHP SDK v5.

php
Route::get('/facebook/login', function(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    $login_link = $fb
            ->getRedirectLoginHelper()
            ->getLoginUrl('https://exmaple.com/facebook/callback', ['email', 'user_events']);
    
    echo 'Log in with Facebook';
});

But if you set the default_redirect_uri callback URL in the config file, you can use the getLoginUrl() wrapper method which will default the callback URL (default_redirect_uri) and permission scope (default_scope) to whatever you set in the config file.

php
$login_link = $fb->getLoginUrl();

Alternatively you can pass the permissions and a custom callback URL to the wrapper to overwrite the default config.

Note: Since the list of permissions sometimes changes but the callback URL usually stays the same, the permissions array is the first argument in the getLoginUrl() wrapper method which is the reverse of the SDK's method getRedirectLoginHelper()->getLoginUrl($url, $permissions).

php
$login_link = $fb->getLoginUrl(['email', 'user_status'], 'https://exmaple.com/facebook/callback');
// Or, if you want to default to the callback URL set in the config
$login_link = $fb->getLoginUrl(['email', 'user_status']);

Obtaining an access token from a callback URL

After the user has clicked on the login link from above and confirmed or denied the app permission requests, they will be redirected to the specified callback URL.

The standard "SDK" way to obtain an access token on the callback URL is as follows:

php
Route::get('/facebook/callback', function(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    try {
        $token = $fb
            ->getRedirectLoginHelper()
            ->getAccessToken();
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // Failed to obtain access token
        dd($e->getMessage());
    }
});

There is a wrapper method for getRedirectLoginHelper()->getAccessToken() in LaravelFacebookSdk called getAccessTokenFromRedirect() that defaults the callback URL to the laravel-facebook-sdk.default_redirect_uri config value.

php
Route::get('/facebook/callback', function(SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fb) {
    try {
        $token = $fb->getAccessTokenFromRedirect();
    } catch (Facebook\Exceptions\FacebookSDKException $e) {
        // Failed to obtain access token
        dd($e->getMessage());
    }
    
    // $token will be null if the user denied the request
    if (! $token) {
        // User denied the request
    }
});

Login From JavaScript

If you're using the JavaScript SDK, you can obtain an access token from the cookie set by the JavaScript SDK.

By default the JavaScript SDK will not set a cookie, so you have to explicitly enable it with cookie: true when you init() the SDK.

javascript
FB.init({
  appId      : 'your-app-id',
  cookie     : true,
  version    : 'v2.10'
});

After you have logged a user in w

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHP

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言