PHPackages                             combindma/laravel-facebook-pixel - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. combindma/laravel-facebook-pixel

ActiveLibrary[API Development](/categories/api)

combindma/laravel-facebook-pixel
================================

Meta pixel integration for Laravel

5.3.2(2mo ago)5279.3k—2.3%15[1 issues](https://github.com/combindma/laravel-facebook-pixel/issues)MITPHPPHP ^8.3CI passing

Since Mar 23Pushed 2mo ago3 watchersCompare

[ Source](https://github.com/combindma/laravel-facebook-pixel)[ Packagist](https://packagist.org/packages/combindma/laravel-facebook-pixel)[ Docs](https://github.com/combindma/laravel-facebook-pixel)[ RSS](/packages/combindma-laravel-facebook-pixel/feed)WikiDiscussions main Synced 3d ago

READMEChangelog (10)Dependencies (41)Versions (26)Used By (0)

Meta Pixel integration for Laravel
==================================

[](#meta-pixel-integration-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/6ef154f7e461185b220105830af2f151e93a28524057088bc9a9a1ff9368a486/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f6d62696e646d612f6c61726176656c2d66616365626f6f6b2d706978656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/combindma/laravel-facebook-pixel)[![GitHub Tests Action Status](https://camo.githubusercontent.com/1012392f619f52592ef31da7d7b923a10ec66dd255890cffcd0c1bfd76d41854/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636f6d62696e646d612f6c61726176656c2d66616365626f6f6b2d706978656c2f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/combindma/laravel-facebook-pixel/actions?query=workflow%3ATests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/5883a8aac01c3594c2c7c6b524883fe0e666aaddfe5cbdbdf31f5735c567aab7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f636f6d62696e646d612f6c61726176656c2d66616365626f6f6b2d706978656c2f6669782d7068702d636f64652d7374796c652d6973737565732e796d6c3f6272616e63683d6d61696e266c6162656c3d636f64652532307374796c65267374796c653d666c61742d737175617265)](https://github.com/combindma/laravel-facebook-pixel/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/b22acd565e55764f7411029e9162015301e7520b21dabfbd290600cdfdd017a4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f6d62696e646d612f6c61726176656c2d66616365626f6f6b2d706978656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/combindma/laravel-facebook-pixel)

A Complete Meta pixel implementation for your Laravel application.

Table of Contents
-----------------

[](#table-of-contents)

- [About Combind Agency](#about-combind-agency)
- [Introduction](#introduction)
- [Upgrading to Version 5](#upgrading-to-version-5)
- [Pre-requisites](#pre-requisites)
    - [Register a Meta Pixel](#register-a-meta-pixel)
    - [Conversions API](#conversions-api)
- [Installation](#installation)
- [Usage - Meta Pixel](#usage---meta-pixel)
    - [Include scripts in Blade](#include-scripts-in-blade)
    - [Flashing data for the next request](#flashing-data-for-the-next-request)
    - [Available Methods](#available-methods)
    - [Custom Events](#custom-events)
    - [Advanced matching](#advanced-matching)
    - [Macroable](#macroable)
- [Usage - Conversions API](#usage---conversions-api)
- [Track and Send Together](#track-and-send-together)
- [Testing](#testing)
- [Contributing](#contributing)
- [Security Vulnerabilities](#security-vulnerabilities)
- [Credits](#credits)
- [License](#license)

About Combind Agency
--------------------

[](#about-combind-agency)

[Combine Agency](https://combind.ma?utm_source=github&utm_medium=banner&utm_campaign=package_name) is a leading web development agency specializing in building innovative and high-performance web applications using modern technologies. Our experienced team of developers, designers, and project managers is dedicated to providing top-notch services tailored to the unique needs of our clients.

If you need assistance with your next project or would like to discuss a custom solution, please feel free to [contact us](mailto:hello@combind.ma) or visit our [website](https://combind.ma?utm_source=github&utm_medium=banner&utm_campaign=package_name) for more information about our services. Let's build something amazing together!

Introduction
------------

[](#introduction)

This package provides a smooth integration of Meta Pixel, along with a straightforward implementation of the latest Conversions API, enhancing your overall experience.

- [Documentation for version 4.0 - older version](README-v4.md)

Upgrading to Version 5
----------------------

[](#upgrading-to-version-5)

If you are upgrading from version 4, please refer to our [Version 5 Migration Guide](upgrade-v4-to-v5.md) for detailed instructions on how to make a smooth transition.

Pre-requisites
--------------

[](#pre-requisites)

### Register a Meta Pixel

[](#register-a-meta-pixel)

To get started with the Meta pixel, you must have a pixel registered: [Read this guide](https://web.facebook.com/business/help/952192354843755).

### Conversions API

[](#conversions-api)

If you plan to use Conversions API then you need to:

#### Obtain An Access Token

[](#obtain-an-access-token)

To use the Conversions API, you need to generate an access token, which will be passed as a parameter in every API call.

Refer to [Conversions API Guide](https://developers.facebook.com/docs/marketing-api/conversions-api/get-started) to learn more.

#### Obtain Your App Secret

[](#obtain-your-app-secret)

Your App Secret is required to generate a valid `appsecret_proof` for every Conversions API request. Facebook uses it to generate an `appsecret_proof` that gets sent with each request for added security, but it's not strictly mandatory for API to work.

You can find it in your **Meta App Dashboard → Settings → Basic → App Secret**.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require combindma/laravel-facebook-pixel
```

Optionally, you can publish the views using:

```
php artisan vendor:publish --tag="meta-pixel-views"
```

You can publish the config file with:

```
php artisan vendor:publish --tag="meta-pixel-config"
```

This is the contents of the published config file:

```
return [
   /*
     * The Meta pixel id, should be a code that looks something like "1202417153106158".
     */
    'pixel_id' => env('META_PIXEL_ID', ''),

    /*
     * The key under which data is saved to the session with flash.
     */
    'session_key' => env('META_PIXEL_SESSION_KEY', config('app.name').'_metaPixel'),

    /*
     * Only if you plan using Conversions API for server events
     * To use the Conversions API, you need an access token. For Documentation please see: https://developers.facebook.com/docs/marketing-api/conversions-api/get-started
     */
    'token' => env('META_PIXEL_TOKEN', ''),

    /*
     * Your Meta App Secret, required to generate a valid appsecret_proof for the Conversions API.
     * Found in your Meta App Dashboard under Settings > Basic.
     */
    'app_secret' => env('META_PIXEL_APP_SECRET'),

    /*
     * Enable or disable advanced matching. Useful for adjusting user privacy.
     */
    'advanced_matching_enabled' => env('META_PIXEL_ADVANCED_MATCHING_ENABLED', true),

    /*
     * Enable or disable script rendering. Useful for local development.
     */
    'enabled' => env('META_PIXEL_ENABLED', false),

    /*
     * Enable or disable logging. Useful for debugging.
     */
    'logging' => env('META_PIXEL_LOGGING', false),

    /*
     * This is used to test server events
     */
    'test_event_code' => env('META_TEST_EVENT_CODE'),
];
```

If you plan on using the [flash-functionality](#flashing-data-for-the-next-request) you must register the MetaPixelMiddleware:

Global Middleware:

```
->withMiddleware(function (Middleware $middleware) {
     $middleware->append(MetaPixelMiddleware::class);
})
```

Or Assigning Middleware to Routes (recommended if you have admin routes):

```
Route::group(['middleware' => [MetaPixelMiddleware::class]], static function () {

});
```

Usage - Meta Pixel
------------------

[](#usage---meta-pixel)

### Include scripts in Blade

[](#include-scripts-in-blade)

Insert head view after opening head tag, and body view after opening body tag

```
>

```

To add an event, use the `track()` function.

```
// CheckoutController.php
use Combindma\FacebookPixel\Facades\MetaPixel;

public function index()
{
    MetaPixel::track('Purchase', ['currency' => 'USD', 'value' => 30.00]);
    return view('thank-you');
}
```

This renders:

```

    /* Meta pixel's base script */

  fbq('track', 'Purchase', {"currency":"USD","value":30});

```

You can also specify a unique event ID for any of your events so that, if you plan using the conversions API you avoid duplications.

```
//For example your order id
MetaPixel::track('Purchase', ['currency' => 'USD', 'value' => 30.00], '123456');

//Or create a unique id using
$eventId = uniqid('ViewContent_', true);
MetaPixel::track('ViewContent', [], $eventId);
```

Calling `track()` multiple times with the same event name during the same request now preserves every event in the order it was added.

```
MetaPixel::track('AddToCart', ['value' => 30.00], 'cart-line-1');
MetaPixel::track('AddToCart', ['value' => 45.00], 'cart-line-2');
```

#### Flashing data for the next request

[](#flashing-data-for-the-next-request)

The package can also set event to render on the next request. This is useful for setting data after an internal redirect.

```
// ContactController.php
use Combindma\FacebookPixel\Facades\MetaPixel;

public function postContact()
{
    // Do contact form stuff...
    MetaPixel::flashEvent('Lead', [
        'content_name' => 'Auto Insurance',
        'content_category' => 'Quote',
        'value' => 400.00,
        'currency' => 'USD'
    ]);
    return redirect()->action('ContactController@getContact');
}
```

After a form submit, the following event will be parsed on the contact page:

```

    /* Meta pixel's base script */

    fbq(
        'track', 'Lead', {
            'content_name': 'Auto Insurance',
            'content_category': 'Quote',
            'value': 400.00,
            'currency': 'USD'
        }
    );

```

### Available Methods

[](#available-methods)

```
use Combindma\FacebookPixel\Facades\MetaPixel;

// Retrieve your Pixel id
$id = MetaPixel::pixelId();
// Set Pixel id on the fly
MetaPixel::setPixelId('XXXXXXXX');
// Set Pixel token on the fly
MetaPixel::setToken('XXXXXXXX');
// Set Pixel testEventCode on the fly
MetaPixel::setTestEventCode('XXXXXXXX');
// Check whether script rendering is enabled
$enabled = MetaPixel::isEnabled(); // true|false
// Enable and disable script rendering on the fly
MetaPixel::enable();
MetaPixel::disable();
// Add event to the event layer (automatically renders right before the pixel script).
MetaPixel::track('eventName', ['attribute' => 'value']);
MetaPixel::track('eventName', ['attribute' => 'value'], 'event_id'); //with an event id
MetaPixel::track('eventName'); //without properties
MetaPixel::track('eventName', [], 'event_id'); //with an event id but without properties
// Flash event for the next request.
MetaPixel::flashEvent('eventName', ['attribute' => 'value']);
MetaPixel::flashEvent('eventName', ['attribute' => 'value'], 'event_id'); //with an event id
MetaPixel::flashEvent('eventName'); //without properties
//Clear the event layer.
MetaPixel::clear();
```

Calling `flashEvent()` multiple times with the same event name during the same request also preserves every event in the order it was added.

### Custom Events

[](#custom-events)

You can also track a specific custom event on your website. This feature is not available for flashed events.

```
use Combindma\FacebookPixel\Facades\MetaPixel;

// In your controller
MetaPixel::trackCustom('CUSTOM-EVENT-NAME', ['custom_parameter' => 'ABC', 'value' => 10.00, 'currency' => 'USD']);
//With an event ID
MetaPixel::trackCustom('CUSTOM-EVENT-NAME', ['custom_parameter' => 'ABC', 'value' => 10.00, 'currency' => 'USD'], 'EVENT_ID');
```

This renders:

```

    /* Meta Pixel's base script */

      fbq('trackCustom', 'CUSTOM-EVENT-NAME', {'custom_parameter': 'ABC', 'value': 10.00, 'currency': 'USD'});
      /* If you specify the event ID */
      fbq('trackCustom', 'CUSTOM-EVENT-NAME', {'custom_parameter': 'ABC', 'value': 10.00, 'currency': 'USD'}, { eventID : 'EVENT_ID' });

```

### Advanced matching

[](#advanced-matching)

This package enables advanced matching by default. It retrieves the authenticated user's email and ID and includes them in the `fbq('init')` call. You can disable it by adding `META_PIXEL_ADVANCED_MATCHING_ENABLED=false` to your `.env` file.

```

        /* Meta pixel's base script */

        fbq('init', '{PixelID}', {
            em: 'email@email.com', //Email provided with Auth::user()->email
            external_id: 12345, //User id provided with Auth::id()
        });

```

### Macroable

[](#macroable)

Adding events to pages can become a repetitive process. Since this package isn't supposed to be opinionated on what your events should look like, the MetaPixel is macroable.

```
use Combindma\FacebookPixel\Facades\MetaPixel;

// Include this in your macroable file
MetaPixel::macro('purchase', function ($product) {
    MetaPixel::track('Purchase', [
        'currency' => 'EUR',
        'value' => $product->price
    ]);
});

//in your controller
MetaPixel::purchase($product);
```

Usage - Conversions API
-----------------------

[](#usage---conversions-api)

If you plan on using [Conversions API](https://developers.facebook.com/docs/marketing-api/conversions-api/get-started), you should specify the following in your `.env` file first:

```
META_PIXEL_TOKEN=your-access-token
META_PIXEL_APP_SECRET=your-app-secret
```

For every request, you should specify a unique event ID to help deduplicate Meta Pixel and Conversions API events.

This is how you can start:

```
use Combindma\FacebookPixel\Facades\MetaPixel;
use FacebookAds\Object\ServerSide\Content;
use FacebookAds\Object\ServerSide\CustomData;
use FacebookAds\Object\ServerSide\DeliveryCategory;
use FacebookAds\Object\ServerSide\UserData;

//Prepare User Data first.
// By default, the IP Address, User Agent and fbc/fbp cookies are added.
$user_data = MetaPixel::userData()->setEmail('joe@eg.com')->setPhone('12345678901');

$content = (new Content())
    ->setProductId('product123')
    ->setQuantity(1)
    ->setDeliveryCategory(DeliveryCategory::HOME_DELIVERY);

$custom_data = (new CustomData())
    ->setContents([$content])
    ->setCurrency('usd')
    ->setValue(123.45);

$eventId = uniqid('prefix_');

//send request
MetaPixel::send('Purchase', $eventId ,$custom_data, $user_data);
```

If you don't specify the `$user_data` parameter, the package retrieves the email and ID from `Auth::user()` when the user is authenticated. It uses the authenticated user ID as the `external_id` value in both Meta Pixel and Conversions API.

```
MetaPixel::send('Purchase', $eventId, $custom_data);
```

Track and Send Together
-----------------------

[](#track-and-send-together)

If you want the package to handle deduplication for you, use `trackAndSend()`. It tracks the browser event and sends the Conversions API event using the same event ID.

```
use Combindma\FacebookPixel\Facades\MetaPixel;
use FacebookAds\Object\ServerSide\CustomData;

$customData = (new CustomData())
    ->setCurrency('usd')
    ->setValue(123.45);

MetaPixel::trackAndSend(
    'Purchase',
    ['currency' => 'USD', 'value' => 123.45],
    $customData,
);
```

If you already have your own event ID, you can still pass it explicitly:

```
MetaPixel::trackAndSend(
    'Purchase',
    ['currency' => 'USD', 'value' => 123.45],
    $customData,
    eventId: 'order-123',
);
```

You can also provide custom `UserData` when needed:

```
use FacebookAds\Object\ServerSide\UserData;

$userData = (new UserData())
    ->setEmail('joe@eg.com');

MetaPixel::trackAndSend(
    'Purchase',
    ['currency' => 'USD', 'value' => 123.45],
    $customData,
    userData: $userData,
);
```

If you want to test server events, you need to specify `META_TEST_EVENT_CODE` in your `.env` file. By default, this test code will be sent in all API requests.

Do not forget to remove it after you finish your server-side tests.

You can use the [Payload Helper](https://developers.facebook.com/docs/marketing-api/conversions-api/payload-helper) to learn more about the requests to send.

Testing
-------

[](#testing)

```
composer test
```

Contributing
------------

[](#contributing)

Contributions are welcome. Please open a pull request with tests for any behavior change or bug fix.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Combind](https://github.com/Combindma)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

60

—

FairBetter than 98% of packages

Maintenance83

Actively maintained with recent releases

Popularity46

Moderate usage in the ecosystem

Community17

Small or concentrated contributor base

Maturity78

Established project with proven stability

 Bus Factor1

Top contributor holds 83.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~77 days

Recently: every ~5 days

Total

25

Last Release

86d ago

Major Versions

1.0.4 → 2.0.02022-02-17

2.0.0 → 3.0.02022-03-08

3.1.0 → 4.0.02023-04-13

4.1.0 → 5.0.02024-04-28

PHP version history (4 changes)1.0.0PHP ^8.0

4.1.0PHP ^8.1

5.0.0PHP ^8.2

5.1.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/81177530?v=4)[Combind](/maintainers/combindma)[@combindma](https://github.com/combindma)

---

Top Contributors

[![omarherri](https://avatars.githubusercontent.com/u/12627384?v=4)](https://github.com/omarherri "omarherri (15 commits)")[![matheusgomes17](https://avatars.githubusercontent.com/u/9301696?v=4)](https://github.com/matheusgomes17 "matheusgomes17 (1 commits)")[![miguelurtado](https://avatars.githubusercontent.com/u/3810528?v=4)](https://github.com/miguelurtado "miguelurtado (1 commits)")[![mprado-vanzolini](https://avatars.githubusercontent.com/u/282682077?v=4)](https://github.com/mprado-vanzolini "mprado-vanzolini (1 commits)")

---

Tags

laravelcombindmameta-pixel

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/combindma-laravel-facebook-pixel/health.svg)

```
[![Health](https://phpackages.com/badges/combindma-laravel-facebook-pixel/health.svg)](https://phpackages.com/packages/combindma-laravel-facebook-pixel)
```

###  Alternatives

[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.1k11.2M102](/packages/dedoc-scramble)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

811334.1k3](/packages/defstudio-telegraph)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)[harris21/laravel-fuse

Circuit breaker for Laravel queue jobs. Protect your workers from cascading failures.

44855.7k](/packages/harris21-laravel-fuse)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
