Laravel
Integrate Swetrix with your Laravel application using Blade templates to track page views, monitor errors, and capture custom events — all while staying privacy-friendly and GDPR-compliant.
Installation
The recommended approach is to add the Swetrix tracking script to your main Blade layout and use Laravel's environment configuration to manage your Project ID.
1. Find your layout file
Laravel applications typically use a shared layout that all pages extend. Depending on your setup, this is usually one of:
resources/views/layouts/app.blade.php(common default)resources/views/components/layout.blade.php(if using Blade components)
If you're using Laravel Breeze or Jetstream, the main layout lives at resources/views/layouts/app.blade.php or resources/views/layouts/guest.blade.php.
2. Add the tracking script
Open your layout file and add the Swetrix script just before the closing </head> tag, and the initialisation snippet just before the closing </body> tag:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ config('app.name', 'Laravel') }}</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
{{-- Swetrix Analytics --}}
<script src="https://swetrix.org/swetrix.js" defer></script>
</head>
<body>
@yield('content')
{{-- Swetrix Analytics --}}
<script>
document.addEventListener('DOMContentLoaded', function () {
swetrix.init('YOUR_PROJECT_ID')
swetrix.trackViews()
})
</script>
<noscript>
<img
src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"
alt=""
referrerpolicy="no-referrer-when-downgrade"
/>
</noscript>
</body>
</html>
Replace YOUR_PROJECT_ID with your actual Project ID from the Swetrix dashboard, otherwise tracking won't work.
3. Disable tracking in development (recommended)
To avoid polluting your analytics with local page views, wrap the snippet in an environment check so it only loads in production:
@production
<script src="https://swetrix.org/swetrix.js" defer></script>
@endproduction
And for the body initialisation:
@production
<script>
document.addEventListener('DOMContentLoaded', function () {
swetrix.init('YOUR_PROJECT_ID')
swetrix.trackViews()
})
</script>
<noscript>
<img
src="https://api.swetrix.com/log/noscript?pid=YOUR_PROJECT_ID"
alt=""
referrerpolicy="no-referrer-when-downgrade"
/>
</noscript>
@endproduction
The @production Blade directive ensures the script is only included when APP_ENV=production.
During development, Swetrix ignores localhost traffic by default. If you want to verify tracking locally without changing your environment, you can temporarily set devMode: true:
swetrix.init('YOUR_PROJECT_ID', { devMode: true })
Remember to remove this before deploying.
Store your Project ID in config (optional)
Rather than hardcoding the Project ID in your Blade template, you can manage it through Laravel's configuration system. This is especially useful if you manage multiple environments or want to keep configuration in one place.
1. Add to your .env file:
SWETRIX_PROJECT_ID=YOUR_PROJECT_ID
2. Register it in config/services.php:
return [
// ...other services
'swetrix' => [
'project_id' => env('SWETRIX_PROJECT_ID'),
],
];
3. Reference it in your Blade template:
@production
<script src="https://swetrix.org/swetrix.js" defer></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
swetrix.init('{{ config('services.swetrix.project_id') }}')
swetrix.trackViews()
})
</script>
<noscript>
<img
src="https://api.swetrix.com/log/noscript?pid={{ config('services.swetrix.project_id') }}"
alt=""
referrerpolicy="no-referrer-when-downgrade"
/>
</noscript>
@endproduction
If you've previously cached your config, run php artisan config:clear to pick up the new values.
Check your installation
Deploy your application (or temporarily set APP_ENV=production) and visit a few pages. Within a minute you should see new pageviews appearing in your Swetrix dashboard.
Error tracking
Enable automatic client-side error monitoring by adding trackErrors() to the initialisation snippet. This captures unhandled JavaScript errors and reports them to Swetrix.
<script>
document.addEventListener('DOMContentLoaded', function () {
swetrix.init('{{ config('services.swetrix.project_id') }}')
swetrix.trackViews()
swetrix.trackErrors()
})
</script>
Errors will appear in the Errors tab of your project dashboard. See the tracking script reference for options like sampleRate and callback.
Tracking custom events
Custom events let you track specific user interactions — form submissions, button clicks, feature usage, and more. Since the Swetrix script is loaded globally, you can call swetrix.track() from any inline script or JavaScript file.
Example: tracking form submissions
Track when users submit a contact form:
<form id="contact-form" method="POST" action="/contact">
@csrf
{{-- form fields --}}
<button type="submit">Send message</button>
</form>
<script>
document.getElementById('contact-form')?.addEventListener('submit', function () {
if (typeof swetrix !== 'undefined') {
swetrix.track({
ev: 'CONTACT_FORM_SUBMITTED',
meta: {
page: window.location.pathname,
},
})
}
})
</script>
Example: tracking outbound links
Track clicks on external links across your site. You can add this to your main layout file:
<script>
document.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('a[href^="http"]').forEach(function (link) {
if (link.hostname !== window.location.hostname) {
link.addEventListener('click', function () {
if (typeof swetrix !== 'undefined') {
swetrix.track({
ev: 'OUTBOUND_CLICK',
meta: { url: link.href },
})
}
})
}
})
})
</script>
Event naming rules
Event names must:
- Contain only English letters (a-Z), numbers (0-9), underscores (
_), and dots (.) - Be fewer than 64 characters
- Start with an English letter
We recommend UPPER_SNAKE_CASE for consistency (e.g. CONTACT_FORM_SUBMITTED, OUTBOUND_CLICK).
Using Swetrix with Livewire or Inertia
If your Laravel application uses Livewire or Inertia.js, the Swetrix script loaded in your layout will still work for initial page loads. However, subsequent navigations happen client-side and won't trigger new page view events automatically.
Swetrix's trackViews() function listens for History API changes, so Inertia navigations (which use pushState under the hood) are tracked automatically in most cases.
For Livewire, if you use wire:navigate for SPA-style navigation, Swetrix will similarly pick up the URL changes. If you experience any gaps, you can manually fire a page view after navigation:
document.addEventListener('livewire:navigated', function () {
if (typeof swetrix !== 'undefined') {
swetrix.pageview({
payload: { pg: window.location.pathname },
})
}
})
Further reading
- Tracking script reference — full API documentation for
init(),track(),trackViews(),trackErrors(), and more. - Swetrix npm package — if you prefer importing Swetrix as an ES module for use with Laravel Mix or Vite.
Help us improve Swetrix
Was this page helpful to you?
