Skip to content

Instantly share code, notes, and snippets.

@cawecoy
Last active November 23, 2021 06:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cawecoy/1c65e4de7bd67f07ff05aaeccea5b997 to your computer and use it in GitHub Desktop.
Save cawecoy/1c65e4de7bd67f07ff05aaeccea5b997 to your computer and use it in GitHub Desktop.
Flash multiple events to Google Tag Manager with spatie/laravel-googletagmanager
<?php
namespace App\Http\Middleware;
use Closure;
class CustomGoogleTagManagerMiddleware extends \Spatie\GoogleTagManager\GoogleTagManagerMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->session->has($this->sessionKey)) {
$data = $this->session->get($this->sessionKey);
if(isset($data[0]) && is_array($data[0])){
foreach ($data as $d) {
$this->googleTagManager->push($d);
}
$this->session->forget($this->sessionKey);
}
}
return parent::handle($request, $next);
}
}
@cawecoy
Copy link
Author

cawecoy commented Oct 12, 2020

Instructions: copy this code to app\Http\Middleware\CustomGoogleTagManagerMiddleware.php and replace \Spatie\GoogleTagManager\GoogleTagManagerMiddleware with \App\Http\Middleware\CustomGoogleTagManagerMiddleware::class in app\Http\Kernel.php.

Now you can flash multiple events to the next request like GoogleTagManager::flash([['event' => 'event1'], ['event' => 'event2'], ['event' => 'event3']]); which will generate something like:

<html>
  <head>
    <script>
        dataLayer.push({
            'event' => 'event1'
        });
        dataLayer.push({
            'event' => 'event2'
        });
        dataLayer.push({
            'event' => 'event3'
        });
    </script>
    <script>/* Google Tag Manager's script */</script>
    <!-- ... -->
  </head>
  <!-- ... -->
</html>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment