suarez/laravel-utm-parameter

A little helper to store and handle utm-parameter

11.1.1 2024-06-21 18:00 UTC

README

Latest Version on Packagist StyleCI Test PHP 8.x Packagist Downloads GitHub Statamic Addon

A lightweight way to handle UTM parameters session-based in your Laravel Application.

@hasUtm('source', 'newsletter')
  <p>Special Content for Newsletter-Subscriber.</p>
@endhasUtm

Installation

Follow these steps to install the Laravel UTM-Parameters package. Guide for Laravel 10 and below.

Open your terminal and navigate to your Laravel project directory. Then, use Composer to install the package:

$ composer require suarez/laravel-utm-parameter

Optionally, you can publish the config file of this package with this command:

php artisan vendor:publish --tag="utm-parameter"

Middleware Configuration

Once the package is installed, you can add the UtmParameters middleware to your Laravel application. Open the bootstrap/app.php file and append the UtmParameters::class inside the web-group.

# Laravel 11
return Application::configure(basePath: dirname(__DIR__))
  ...
  ->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
      Suarez\UtmParameter\Middleware\UtmParameters::class,
      /* ... keep the existing middleware here */
    ]);
  })
  ...

Also, take a look at how to set an alias for the middleware.

Use as Facade

If you prefer not to use it as middleware, you can utilize the UtmParameter Facade directly in your controllers or other parts of your application. Once the boot($request)-method is called, you have access to it at any place. For example:

use Suarez\UtmParameter\Facades\UtmParameter;

// Inside a controller method
class IndexController {
  public function index(Request $request)
  {
      UtmParameter::boot($request);
  }
}

class SomeDifferentController {
  public function index(Request $request)
  {
      $source = UtmParameter::get('source');
  }
}

Configuration

The configuration file config/utm-parameter.php allows you to control the behavior of the UTM parameters handling.

<?php

return [
  /*
   * Control Overwriting UTM Parameters (default: false)
   *
   * This setting determines how UTM parameters are handled within a user's session.
   *
   * - Enabled (true): New UTM parameters will overwrite existing ones during the session.
   * - Disabled (false): The initial UTM parameters will persist throughout the session.
   */
  'override_utm_parameters' => false,

  /*
   * Session Key for UTM Parameters (default: 'utm')
   *
   * This key specifies the name used to access and store UTM parameters within the session data.
   *
   * If you're already using 'utm' for another purpose in your application,
   * you can customize this key to avoid conflicts.
   * Simply provide your preferred key name as a string value.
   */
  'session_key' => 'utm',

  /*
    * Allowed UTM Parameters (default: ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'utm_campaign_id'])
    *
    * This setting defines the UTM parameters that are allowed within your application.
    *
    * In this array, you can specify a list of allowed UTM parameter names. Each parameter should be listed as a string.
    * Only parameters from this list will be stored and processed in the session.
    * and any parameter without the 'utm_' prefix will be ignored regardless of its inclusion in this list.
    *
    * Example: To only allow the basic UTM parameters (source, medium, and campaign), you could update the array like this:
    *
    * 'allowed_utm_parameters' => [
    *     'utm_source',
    *     'utm_medium',
    *     'utm_campaign',
    * ],
    */
    'allowed_utm_parameters' => [
        'utm_source',
        'utm_medium',
        'utm_campaign',
        'utm_term',
        'utm_content',
        'utm_campaign_id'
    ],
];

Usage

get_all_utm()

To get an array of all UTM parameters, use this helper: get_all_utm().

$parameter = get_all_utm();

get_utm()

If you need to retrieve certain UTM parameters, use get_utm('source|medium|campaign|term|content').

 <p>You came from {{ get_utm('source') }}</p>
// Some Task in your Class
public function someTask()
{
  return match(get_utm('source')) {
    'bing' => Bing::class,
    'google' => Google::class,
    'duckduckgo' => DuckDuckGo::class,
    'newsletter' => Newsletter::class,
    default => Default::class
  };
}

// Render a view based on an utm_source
Route::get('/', function () {
  return match(get_utm('source')) {
        'newsletter' => view('newsletter'),
        default => view('welcome')
    };
});

has_utm()

Sometimes you want to show or do something, if user might have some or specific utm-parameters.

Simply use:

  • has_utm('source|medium|campaign|term|content', 'optional-value')
  • has_not_utm('source|medium|campaign|term|content', 'optional-value')
@hasUtm('source', 'corporate-partner')
  <div>Some corporate partner related stuff</div>
@endhasUtm

@hasNotUtm('term')
  <p>You have any term.</p>
@endhasNotUtm
 if (has_utm('campaign', 'special-sale')) {
   redirect('to/special-sale/page');
 }

 if (has_not_utm('campaign', 'newsletter')) {
   session()->flash('Did you know, we have a newsletter?');
 }

contains_utm()

You can conditionally show or perform actions based on the presence or absence of a portion of an UTM parameters using contains.

Simply use:

  • contains_utm('source|medium|campaign|term|content', 'value')
  • contains_not_utm('source|medium|campaign|term|content', 'value')
@containsUtm('campaign', 'weekly')
  <div>Some Weekly related stuff</div>
@endhasUtm

@containsNotUtm('campaign', 'sales')
  <p>Some not Sales stuff</p>
@endhasNotUtm
 if (contains_utm('campaign', 'weekly')) {
   redirect('to/special/page');
 }

 if (contains_not_utm('campaign', 'sale')) {
   session()->flash('Did you know, we have a newsletter?');
 }

Extending the Middleware

You can extend the middleware to customize the behavior of accepting UTM parameters. For example, you can override the shouldAcceptUtmParameter method.

First, create a new middleware using Artisan:

php artisan make:middleware CustomMiddleware

Then, update the new middleware to extend UtmParameters and override the shouldAcceptUtmParameter method:

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Suarez\UtmParameter\Middleware\UtmParameters;

class CustomMiddleware extends UtmParameters
{
    /**
     * Determines whether the given request/response pair should accept UTM-Parameters.
     *
     * @param \Illuminate\Http\Request  $request
     *
     * @return bool
     */
    protected function shouldAcceptUtmParameter(Request $request)
    {
        return $request->isMethod('GET') || $request->isMethod('POST');
    }
}

Finally, update your bootstrap/app.php to use the CustomMiddleware:

# bootstrap/app.php
use App\Http\Middleware\CustomMiddleware;

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [
        CustomMiddleware::class,
        // other middleware...
    ]);
})

Resources

Explore additional use cases and resources on the wiki pages

Inspirations

License

The Laravel UTM-Parameters package is open-sourced software licensed under the MIT license.