Skip to content

Laravel quickstart

Add Insights Orbit to a Laravel website, send events from the page and from your server, wait for consent and check that they arrive.

Tutorial6 min read

In about 15 minutes you add Insights Orbit to a Laravel website for Northwilds. Page views count on every page, a button sends a Brochure requested event from the browser, and a booking sends Trip booked with its revenue from your server, where no ad blocker can hide it. An optional banner asks visitors before anything is counted in the browser.

Tested with: Laravel 13.40, PHP 8.5, php artisan serve.

Before you start

You need:

  • A site in Insights Orbit with your website's addresses under Site settings. Add localhost too while you build on your computer, or events from the browser answer 403. See Add your first site.
  • The site key, from the site's Install screen. It isn't a secret.
  • An API key that sends events, for step 5. An Admin makes it under API keys with Send events ticked. It starts with ins_live_ and is a secret. See API keys.
  • PHP 8.3 or later and Composer.

1Create the project

Shell
composer create-project laravel/laravel northwilds-sitecd northwilds-site

Add the settings to config/services.php, inside the array it returns:

PHP
// config/services.php'insights' => [    'url' => env('INSIGHTS_URL', 'https://api.bifrostorbit.com/insights/v1'),    'site' => env('INSIGHTS_SITE'),    'key' => env('INSIGHTS_API_KEY'),],
.envShell
INSIGHTS_SITE=SITE_KEYINSIGHTS_API_KEY=ins_live_…

For staging, set INSIGHTS_URL to https://api-stage.bifrostorbit.com/insights/v1.

2Add the script

A layout component puts the script on every page, with a small analytics() helper that calls the script or queues the call until it has loaded:

Blade
{{-- resources/views/components/layout.blade.php --}}<!DOCTYPE html><html lang="en"><head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width, initial-scale=1">    <title>{{ $title ?? 'Northwilds' }}</title>    @if (config('services.insights.site'))        <script defer data-site="{{ config('services.insights.site') }}" src="{{ config('services.insights.url') }}/script.js"></script>    @endif    <script>        function analytics(...command) {            if (window.insights?.track) window.insights[command[0]](...command.slice(1));            else (window.insights ??= { q: [] }).q.push(command);        }    </script></head><body>    <header>        <a href="/">Northwilds</a> <a href="/trips/lofoten-ski-touring">Trips</a>    </header>    {{ $slot }}</body></html>

Don't name the helper insights: that name belongs to the script.

Add a home page and the routes:

Blade
{{-- resources/views/home.blade.php --}}<x-layout>    <main>        <h1>Northwilds</h1>        <p>Guided trips in the far north.</p>        <a href="/trips/lofoten-ski-touring">See the trips</a>    </main></x-layout>
PHP
// routes/web.php<?phpuse App\Services\Insights;use Illuminate\Support\Facades\Route;use Illuminate\Support\Str;Route::view('/', 'home');Route::view('/trips/lofoten-ski-touring', 'trip');

3Send events from the page

The trip page has a brochure button and a booking form:

Blade
{{-- resources/views/trip.blade.php --}}<x-layout title="Lofoten ski touring week">    <main>        <h1>Lofoten ski touring week</h1>        <p>Seven days of ski touring above the fjords, from €2,450.</p>        @if (session('booked'))            <p>Thank you. Your booking {{ session('booked') }} is confirmed.</p>        @else            <form method="post" action="/trips/lofoten-ski-touring/book">                @csrf                <button type="submit">Book the trip</button>            </form>        @endif        <button type="button" id="brochure">Send me the brochure</button>    </main>    <script>        document.getElementById('brochure').addEventListener('click', (event) => {            analytics('track', 'Brochure requested', { trip: 'lofoten-ski-touring' });            event.target.textContent = 'On its way';            event.target.disabled = true;        });    </script></x-layout>
  • Event names are what goals look for, so use plain words. Details are text, numbers or true or false; never names or email addresses. Send your own events has the limits.
  • The booking form also sends the automatic Form sent event when it is submitted. Name it with name="booking" on the form to tell forms apart.
  • To count it as success, an Editor adds a goal under Goals that sends the event Brochure requested. See Set up goals.

Insights Orbit uses no cookies and keeps no personal data. Whether you still ask first is your decision with your adviser. See What to write in your privacy notice. To ask first, add data-consent="wait" to the script in the layout:

Blade
<script defer data-site="{{ config('services.insights.site') }}" data-consent="wait" src="{{ config('services.insights.url') }}/script.js"></script>

The script now counts nothing until the page calls insights.consent(). It doesn't remember the answer, so your banner keeps it and calls consent on every page. Add it to the layout, after {{ $slot }}:

Blade
<aside id="consent" aria-label="Analytics" hidden>    <p>May we count your visit? We use no cookies and keep no personal data.</p>    <button type="button" data-answer="yes">Yes</button>    <button type="button" data-answer="no">No thanks</button></aside><script>    (() => {        const key = 'northwilds-analytics';        const banner = document.getElementById('consent');        const saved = localStorage.getItem(key);        if (saved === 'yes') analytics('consent');        banner.hidden = saved !== null;        banner.querySelectorAll('[data-answer]').forEach((button) => {            button.addEventListener('click', () => {                localStorage.setItem(key, button.dataset.answer);                banner.hidden = true;                analytics('consent', button.dataset.answer === 'yes');            });        });    })();</script>
  • The page where the visitor answers still counts: its page view waits in memory and is sent the moment they say yes. Pages they left before answering aren't counted.
  • No thanks drops what is waiting, and nothing is sent on later pages.
  • Server events in step 5 don't depend on the banner. They carry no visitor, only what your server sends.

5Send events from your server

Some things are confirmed on your server, such as a booking or a payment. Send them to the server API with the API key:

PHP
// app/Services/Insights.php<?phpnamespace App\Services;use Illuminate\Http\Client\ConnectionException;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Log;class Insights{    public function event(string $name, string $id, array $properties = [], ?float $revenue = null, ?string $currency = null): void    {        $key = config('services.insights.key');        if (! $key) {            return;        }        $event = array_filter([            'id' => $id,            'name' => $name,            'properties' => $properties ?: null,            'revenue' => $revenue,            'currency' => $currency,        ], fn ($value) => $value !== null);        try {            $response = Http::withToken($key)                ->timeout(5)                ->post(config('services.insights.url').'/server/events', [                    'site' => config('services.insights.site'),                    'events' => [$event],                ]);        } catch (ConnectionException $error) {            Log::warning('Insights Orbit could not be reached', ['error' => $error->getMessage()]);            return;        }        if ($response->failed()) {            Log::warning('Insights Orbit did not take the event', ['status' => $response->status(), 'error' => $response->json('error')]);        }    }}

Add the booking route to routes/web.php:

PHP
Route::post('/trips/lofoten-ski-touring/book', function (Insights $insights) {    $reference = 'NW-'.Str::upper(Str::random(6));    $insights->event('Trip booked', $reference, ['trip' => 'lofoten-ski-touring'], 2450, 'EUR');    return redirect('/trips/lofoten-ski-touring')->with('booked', $reference);});
  • id is your own reference. The same id sent again within eight days counts once, so sending again after a timeout is safe.
  • A booking never fails because of analytics: a wrong key or Insights Orbit out of reach only writes a warning to the log.
  • Server events have no visitor or visit, and their device is server. Each one counts as a goal completion of its own.
  • The key stays in .env on the server. Never put it in a page.

6Check that events arrive

Run php artisan serve, open http://127.0.0.1:8000, go to Trips, select Send me the brochure, then Book the trip. If you added the banner, select Yes first.

  • In the browser: the Network tab shows POST requests to collect answering 202. The booking itself goes from your server, so look for it in Insights Orbit.
  • In Insights Orbit: Right now on the overview shows you on /trips/lofoten-ski-touring, and Events lists Brochure requested, Form sent and Trip booked within a few seconds.
  • In the log: storage/logs/laravel.log has a warning if the server API refused the event, with its code, such as unauthorized for a wrong key.
  • From the API, on the Growth plan, with a key that reads events:
Shell
curl "https://api.bifrostorbit.com/insights/v1/events?site=SITE_KEY&name=Trip%20booked" \  -H "Authorization: Bearer ins_live_…"

It answers with the booking, its revenue (2450, EUR) and device server.

Nothing arrives from the browser? Browsers with Do Not Track or Global Privacy Control on, and automated browsers, send nothing on purpose. Troubleshooting for developers lists every other cause.

Next steps

Was this page helpful?

Read next