PHPackages                             moesif/moesif-laravel - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. moesif/moesif-laravel

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

moesif/moesif-laravel
=====================

Moesif Collection/Data Ingestion Middleware for Laravel

2.0.7(1y ago)1065.8k↓21.4%5Apache-2.0PHPPHP &gt;=5.4.0CI failing

Since Nov 2Pushed 1y ago7 watchersCompare

[ Source](https://github.com/Moesif/moesif-laravel)[ Packagist](https://packagist.org/packages/moesif/moesif-laravel)[ Docs](https://moesif.com)[ RSS](/packages/moesif-moesif-laravel/feed)WikiDiscussions master Synced 1mo ago

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

Moesif Laravel Middlware
========================

[](#moesif-laravel-middlware)

[![Built For](https://camo.githubusercontent.com/5dc33dc453936987e8423b2e93ebdb1955ecc7187cc664824ca4a957aecb85c2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275696c74253230666f722d6c61726176656c2d626c75652e737667)](http://laravel.com)[![Latest Version](https://camo.githubusercontent.com/bdffd74e4712ce67b7eee626e3e87ab666bffef43a4eb8d4a052e986b28cf59b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6f657369662f6d6f657369662d6c61726176656c2e737667)](https://packagist.org/packages/moesif/moesif-laravel)[![Total Downloads](https://camo.githubusercontent.com/664ee5023498794a28b30a7900d9f9129571eaa9c290e6be414d52cbb7c86fb3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6f657369662f6d6f657369662d6c61726176656c2e737667)](https://packagist.org/packages/moesif/moesif-laravel)[![Software License](https://camo.githubusercontent.com/109222cb0d1f59ed2e77b56722653623fa45f93e2bb201a6eef8561d26a52185/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d417061636865253230322e302d677265656e2e737667)](https://raw.githubusercontent.com/Moesif/moesif-laravel/master/LICENSE)[![Source Code](https://camo.githubusercontent.com/5add2478e7d99103a5de4f462acb982bdde924462b013391214d74ef0c9512b2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f6d6f657369662f6d6f657369662d6c61726176656c2e7376673f7374796c653d736f6369616c)](https://github.com/moesif/moesif-laravel)

[Source Code on GitHub](https://github.com/moesif/moesif-laravel)

Middleware for PHP Laravel (&gt; 5.1) to automatically log API Calls and sends to [Moesif](https://www.moesif.com) for API analytics and log analysis

### Laravel 4.2

[](#laravel-42)

A [Moesif SDK](https://github.com/Moesif/moesif-laravel4.2) is available for Laravel 4.2. Credit for creating this goes to [jonnypickett](https://github.com/jonnypickett/).

How to install
--------------

[](#how-to-install)

Via Composer

```
$ composer require moesif/moesif-laravel
```

or add 'moesif/moesif-laravel' to your composer.json file accordingly.

How to use
----------

[](#how-to-use)

### Add Service Provider

[](#add-service-provider)

```
// In config/app.php

'providers' => [
  /*
   * Application Service Providers...
   */
    Moesif\Middleware\MoesifLaravelServiceProvider::class,
];
```

### Add to Middleware

[](#add-to-middleware)

If website root is your API, add to the root level:

```
// In App/Http/Kernel.php

protected $middleware = [
  /*
   * The application's global HTTP middleware stack.
   *
   * These middleware are run during every request to your application.
   */
   \Moesif\Middleware\MoesifLaravel::class,
];
```

If you only want to add tracking for APIs under specific route group, add to your route group, but be sure to remove from the global middleware stack from above global list.

```
// In App/Http/Kernel.php

protected $middlewareGroups = [
  /**
   * The application's API route middleware group.
   */
   'api' => [
        //
        \Moesif\Middleware\MoesifLaravel::class,
    ],
];
```

To track only certain routes, use route specific middleware setup.

### Publish the package config file

[](#publish-the-package-config-file)

```
$ php artisan vendor:publish --provider="Moesif\Middleware\MoesifLaravelServiceProvider"
```

### Setup config

[](#setup-config)

Edit `config/moesif.php` file.

```
// In config/moesif.php

return [
    //
    'applicationId' => 'Your Moesif Application Id',
    'logBody' => true,
];
```

Your Moesif Application Id can be found in the [*Moesif Portal*](https://www.moesif.com/). After signing up for a Moesif account, your Moesif Application Id will be displayed during the onboarding steps.

You can always find your Moesif Application Id at any time by logging into the [*Moesif Portal*](https://www.moesif.com/), click on the top right menu, and then clicking *Installation*.

For other configuration options, see below.

Configuration options
---------------------

[](#configuration-options)

**To support Laravel [configuration caching](https://laravel.com/docs/8.x/configuration#configuration-caching), some configuration options have moved into a separate config class for v2. See [Migration Guide v1.x.x to v2.x.x](#migration-guide-v1xx-to-v2xx)**

You can define Moesif configuration options in the `config/moesif.php` file.

#### **`applicationId`**

[](#applicationid)

Type: `String`Required, a string that identifies your application.

#### **`disableForking`**

[](#disableforking)

Type: `Boolean`Optional, If true, this will disable forking. For the best performance, the SDK forks a process to send events by default. However, this requires your PHP environment to not have `exec` disabled via `disable_functions`.

#### **`debug`**

[](#debug)

Type: `Boolean`Optional, If true, will print debug messages using Illuminate\\Support\\Facades\\Log

#### **`logBody`**

[](#logbody)

Type: `Boolean`Optional, Default true, Set to false to remove logging request and response body to Moesif.

#### **`apiVersion`**

[](#apiversion)

Type: `String`Optional, a string to specify an API Version such as 1.0.1, allowing easier filters.

### **`configClass`**

[](#configclass)

Type: `String`Optional, a string for the full path (including namespaces) to a class containing additional functions. The class can reside in any namespace, as long as the full namespace is provided.

example:

```
return [
    ...
    'configClass' => 'MyApp\\MyConfigs\\CustomMoesifConfig',
    ...
];
```

Configuration class
-------------------

[](#configuration-class)

Because configuration hooks and functions cannot be placed in the `config/moesif.php` file, these reside in a PHP class that you create. Set the path to this class using the `configClass` option. You can define any of the following hooks:

#### **`identifyUserId`**

[](#identifyuserid)

Type: `($request, $response) => String`Optional, a function that takes a $request and $response and return a string for userId. Moesif automatically obtains end userId via $request-&gt;user()\['id'\], In case you use a non standard way of injecting user into $request or want to override userId, you can do so with identifyUserId.

#### **`identifyCompanyId`**

[](#identifycompanyid)

Type: `($request, $response) => String`Optional, a function that takes a $request and $response and return a string for companyId.

#### **`identifySessionId`**

[](#identifysessionid)

Type: `($request, $response) => String`Optional, a function that takes a $request and $response and return a string for sessionId. Moesif automatically sessionizes by processing at your data, but you can override this via identifySessionId if you're not happy with the results.

#### **`getMetadata`**

[](#getmetadata)

Type: `($request, $response) => Associative Array`Optional, a function that takes a $request and $response and returns $metdata which is an associative array representation of JSON.

#### **`maskRequestHeaders`**

[](#maskrequestheaders)

Type: `$headers => $headers`Optional, a function that takes a $headers, which is an associative array, and returns an associative array with your sensitive headers removed/masked.

#### **`maskRequestBody`**

[](#maskrequestbody)

Type: `$body => $body`Optional, a function that takes a $body, which is an associative array representation of JSON, and returns an associative array with any information removed.

#### **`maskResponseHeaders`**

[](#maskresponseheaders)

Type: `$headers => $headers`Optional, same as above, but for Responses.

#### **`maskResponseBody`**

[](#maskresponsebody)

Type: `$body => $body`Optional, same as above, but for Responses.

#### **`skip`**

[](#skip)

Type: `($request, $response) => String`Optional, a function that takes a $request and $response and returns true if this API call should be not be sent to Moesif.

Example config class

```
namespace MyApp\MyConfigs;

class CustomMoesifConfig
{
    public function maskRequestHeaders($headers) {
      $headers['header5'] = '';
      return $headers;
    }

    public function maskRequestBody($body) {
      return $body;
    }

    public function maskResponseHeaders($headers) {
      $headers['header2'] = 'XXXXXX';
      return $headers;
    }

    public function maskResponseBody($body) {
      return $body;
    }

    public function identifyUserId($request, $response) {
      if (is_null($request->user())) {
        return null;
      } else {
        $user = $request->user();
        return $user['id'];
      }
    }

    public function identifyCompanyId($request, $response) {
      return "67890";
    }

    public function identifySessionId($request, $response) {
      if ($request->hasSession()) {
        return $request->session()->getId();
      } else {
        return null;
      }
    }

    public function getMetadata($request, $response) {
      return array("foo"=>"a", "boo"=>"b");
    }

    public function skip($request, $response) {
      $myurl = $request->fullUrl();
      if (strpos($myurl, '/health') !== false) {
        return true;
      }
      return false;
    }
}
```

Update a Single User
--------------------

[](#update-a-single-user)

Create or update a user profile in Moesif. The metadata field can be any customer demographic or other info you want to store. Only the `user_id` field is required.

```
use Moesif\Middleware\MoesifLaravel;

// Only userId is required.
// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#users for campaign schema
// metadata can be any custom object
$user = array(
    "user_id" => "12345",
    "company_id" => "67890", // If set, associate user with a company object
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "email" => "john@acmeinc.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    )
);

$middleware = new MoesifLaravel();
$middleware->updateUser($user);
```

The `metadata` field can be any custom data you want to set on the user. The `user_id` field is required.

Update Users in Batch
---------------------

[](#update-users-in-batch)

Similar to updateUser, but used to update a list of users in one batch. Only the `user_id` field is required.

```
use Moesif\Middleware\MoesifLaravel;

$userA = array(
    "user_id" => "12345",
    "company_id" => "67890", // If set, associate user with a company object
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "email" => "john@acmeinc.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    )
);

$userB = array(
    "user_id" => "12345",
    "company_id" => "67890", // If set, associate user with a company object
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "email" => "john@acmeinc.com",
        "first_name" => "John",
        "last_name" => "Doe",
        "title" => "Software Engineer",
        "sales_info" => array(
            "stage" => "Customer",
            "lifetime_value" => 24000,
            "account_owner" => "mary@contoso.com"
        )
    )
);

$users = array($userA);

$middleware = new MoesifLaravel();
$middleware->updateUsersBatch($users);
```

The `metadata` field can be any custom data you want to set on the user. The `user_id` field is required.

Update a Single Company
-----------------------

[](#update-a-single-company)

Create or update a company profile in Moesif. The metadata field can be any company demographic or other info you want to store. Only the `company_id` field is required.

```
use Moesif\Middleware\MoesifLaravel;

// Only companyId is required.
// Campaign object is optional, but useful if you want to track ROI of acquisition channels
// See https://www.moesif.com/docs/api#update-a-company for campaign schema
// metadata can be any custom object
$company = array(
    "company_id" => "67890",
    "company_domain" => "acmeinc.com", // If domain is set, Moesif will enrich your profiles with publicly available info
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "org_name" => "Acme, Inc",
        "plan_name" => "Free",
        "deal_stage" => "Lead",
        "mrr" => 24000,
        "demographics" => array(
            "alexa_ranking" => 500000,
            "employee_count" => 47
        )
    )
);

$middleware = new MoesifLaravel();
$middleware->updateCompany($company);
```

The `metadata` field can be any custom data you want to set on the company. The `company_id` field is required.

Update Companies in Batch
-------------------------

[](#update-companies-in-batch)

Similar to update\_company, but used to update a list of companies in one batch. Only the `company_id` field is required.

```
use Moesif\Middleware\MoesifLaravel;

$companyA = array(
    "company_id" => "67890",
    "company_domain" => "acmeinc.com", // If domain is set, Moesif will enrich your profiles with publicly available info
    "campaign" => array(
        "utm_source" => "google",
        "utm_medium" => "cpc",
        "utm_campaign" => "adwords",
        "utm_term" => "api+tooling",
        "utm_content" => "landing"
    ),
    "metadata" => array(
        "org_name" => "Acme, Inc",
        "plan_name" => "Free",
        "deal_stage" => "Lead",
        "mrr" => 24000,
        "demographics" => array(
            "alexa_ranking" => 500000,
            "employee_count" => 47
        )
    )
);

$companies = array($companyA);

$middleware = new MoesifLaravel();
$middleware->updateCompaniesBatch($companies);
```

The `metadata` field can be any custom data you want to set on the company. The `company_id` field is required.

Credits for Moesif Laravel SDK
------------------------------

[](#credits-for-moesif-laravel-sdk)

- Parts of queuing &amp; sending data via forked non-blocking process is based on Mixpanel's PHP client code which is open sourced under Apache License, Version 2.0.

Additional Tips:
----------------

[](#additional-tips)

- The forked (i.e. non-blocking way) of sending data is using exec() with a cURL command. The Php exec() command can be successful but the cURL itself may have 401 errors. So after integration, if you don't see events and data show up in your Moesif Dash. Please turn on debug option, then the cURL command itself will logged. You can execute that cURL command and see what the issues are. The most common thing to check is if the Application ID is set correctly.

In case you've exec() as a disabled function, you could set configuration option `disableForking` to `true` to send data to Moesif using curl PHP extension.

Troubleshooting
---------------

[](#troubleshooting)

### exec() must exist/exec() must be enabled

[](#exec-must-existexec-must-be-enabled)

By default, Moesif forks a process to log API calls in an asynchronous method, which requires your PHP environment to have exec() enabled. For highest performance, the recommended fix is to ensure exec() is enabled for your hosting environment:

- [Instructions for DigitalOcean](https://www.digitalocean.com/community/questions/why-is-php-exec-not-working-on-digitalocean)
- [Instructions for Namecheap](https://www.namecheap.com/support/knowledgebase/article.aspx/9396/2219/how-to-enable-exec)

If you cannot enable exec (such as for shared hosting environments), you can disable forking by adding the following to your `moesif.php`.

```
return [
    'applicationId' => 'Your Moesif Application Id',
    'disableForking' => true,
];
```

### The PHP JSON extension is required.

[](#the-php-json-extension-is-required)

Make sure you install PHP with the JSON Extension enabled [More Info](https://stackoverflow.com/questions/7318191/enable-json-encode-in-php).

### The PHP cURL extension is required

[](#the-php-curl-extension-is-required)

This error happens when you disabled forking and you do not have the cURL PHP extension enabled. The recommended fix is to enable forking by setting `disableForking` to false in your `moesif.php`. Otherwise, ensure you have enabled the PHP CURL extension. [More info](https://www.php.net/manual/en/curl.installation.php).

### No events show up in Moesif

[](#no-events-show-up-in-moesif)

Because Moesif forks a process, you may not see all errors from the child process. A common case for event not showing up is due to an incorrect application id. To see debug logs, you can add the following to your `moesif.php`:

```
// In config/moesif.php

return [
    //
    'applicationId' => 'Your Moesif Application Id',
    'debug' => true,
];
```

Test Laravel App with Moesif Integrated
---------------------------------------

[](#test-laravel-app-with-moesif-integrated)

[Moesif Laravel Tests](https://github.com/Moesif/moesif-laravel-tests)

An Example Laravel App with Moesif Integrated
---------------------------------------------

[](#an-example-laravel-app-with-moesif-integrated)

[Moesif Laravel Example](https://github.com/Moesif/moesif-laravel-example)

Be sure to update cache after changing config:
----------------------------------------------

[](#be-sure-to-update-cache-after-changing-config)

If you enabled config cache, after you update the configuration, please be sure to run `php artisan config:cache` again to ensure configuration is updated.

Other integrations
------------------

[](#other-integrations)

To view more documentation on integration options, please visit **[the Integration Options Documentation](https://www.moesif.com/docs/getting-started/integration-options/).**

Migration Guide v1.x.x to v2.x.x
--------------------------------

[](#migration-guide-v1xx-to-v2xx)

v2.x.x now supports Laravel config caching. However, `config:cache` does not allow function closures in config files ([See issue on github](https://github.com/laravel/framework/issues/24103)) so the SDK configuration has changed in v2.x.x. To migrate, you will need to move any functions from your `config/moesif.php` into a separate class such as CustomMoesifConfig. Then, reference this class using `configClass`.

For example, if you had these previously:

```
$identifyUserId = function($request, $response) {
    // Your custom code that returns a user id string
    $user = $request->user();
    if ($request->user()) {
        return $user->id;
    }
    return NULL;
};

return [
  ...,
  'identifyUserId' => $identifyUserId,
]
```

In V2.X.X, you would do this:

- Create a new class like this:

```
namespace MyApp\MyConfigs;

class CustomMoesifConfig
{
    public function identifyUserId($request, $response) {
      if (is_null($request->user())) {
        return null;
      } else {
        $user = $request->user();
        return $user['id'];
      }
    }

    // add other methods for closure based configs.
}
```

- In your `moesif.php` in the config folder:

```
return [
  ...,
  'configClass' => 'MyApp\\MyConfigs\\CustomMoesifConfig',
]
```

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance37

Infrequent updates — may be unmaintained

Popularity38

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity70

Established project with proven stability

 Bus Factor1

Top contributor holds 50.6% 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 ~79 days

Recently: every ~365 days

Total

38

Last Release

566d ago

Major Versions

1.4.11 → 2.0.02020-10-06

### Community

Maintainers

![](https://www.gravatar.com/avatar/3b0b32ccd8f8b52e30bef1135e332fb06e0197436e66ffe2555f5a49cda532ea?d=identicon)[xingwang](/maintainers/xingwang)

![](https://www.gravatar.com/avatar/01d3256f8e2dc2c3e1a7934d4b11d9dccc7936c1b80dea9a0880e73d3448eeae?d=identicon)[moesif](/maintainers/moesif)

![](https://www.gravatar.com/avatar/fc618c4daa24676ee9242436cafb63fec92912c550d2c26c09debdd6d00e65c1?d=identicon)[dkm199](/maintainers/dkm199)

![](https://www.gravatar.com/avatar/fb928dd5f778f90a12145682b148d6ca4ba5e8a037f82b00c5ea289f85ae2b92?d=identicon)[keyur9](/maintainers/keyur9)

---

Top Contributors

[![dgilling](https://avatars.githubusercontent.com/u/9476006?v=4)](https://github.com/dgilling "dgilling (41 commits)")[![xinghengwang](https://avatars.githubusercontent.com/u/6666687?v=4)](https://github.com/xinghengwang "xinghengwang (20 commits)")[![matthewoates](https://avatars.githubusercontent.com/u/3092315?v=4)](https://github.com/matthewoates "matthewoates (9 commits)")[![keyur9](https://avatars.githubusercontent.com/u/9168390?v=4)](https://github.com/keyur9 "keyur9 (6 commits)")[![dkm199](https://avatars.githubusercontent.com/u/6922402?v=4)](https://github.com/dkm199 "dkm199 (4 commits)")[![bsormagec](https://avatars.githubusercontent.com/u/965219?v=4)](https://github.com/bsormagec "bsormagec (1 commits)")

---

Tags

api-managementinterceptorlaravellaravel-middlewareloggerlogger-middlewarelogginglogging-librarylogmiddlewareapilaravelloggingdebuggingMoesif

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/moesif-moesif-laravel/health.svg)

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

###  Alternatives

[ytake/laravel-fluent-logger

fluent logger for laravel and lumen

63541.6k1](/packages/ytake-laravel-fluent-logger)[hosmelq/laravel-logsnag

Integrate the power of LogSnag's real-time event tracking into your Laravel application.

237.9k](/packages/hosmelq-laravel-logsnag)

PHPackages © 2026

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