Search by

internetguru / laravel-common

internetguru

There is no license information available for the latest version (v10.0.0) of this package.

Package info

github.com/internetguru/laravel-common

pkg:composer/internetguru/laravel-common

Statistics

Installs: 5 830

Dependents: 3

Suggesters: 0

Stars: 0

Open Issues: 5

v10.0.0 2026-11-20 15:39 UTC

This package is auto-updated.

Last update: 2026-11-21 18:13:29 UTC


README

This package provides handy utilities for Laravel applications.

Branch Status Code Coverage
Main tests coverage

Table of Contents

Installation

You can install the package via Composer:

composer require internetguru/laravel-common

The CommonServiceProvider is auto-discovered via composer.json extra.laravel.providers. No manual registration is needed for the core provider.

Vite

Register the dev watch plugin in the application's vite.config.js:

import igDevWatch from './vendor/internetguru/laravel-common/resources/js/vite-dev-watch.js';

plugins: [laravel({ ... }), igDevWatch()],

The dev server then skips what it never bundles: vendor/ apart from the Internet Guru packages, and storage/framework and storage/logs. Watching them uses up the Linux limit on watched files that every application on the machine shares. A build never loads the plugin.

Run Tests Locally

To run the tests manually, you can use the following command:

./test.sh

It runs the JavaScript tests (Vitest, tests/js) and then the PHPUnit tests in Docker. To run only the JavaScript tests, use npm test.

Shared Tests

The package ships Pest tests that every application built on it should pass. Register them from one test file, e.g. tests/Feature/CommonTest.php:

use InternetGuru\LaravelCommon\Testing\CommonTests;

CommonTests::register(languages: ['en', 'cs'], demo: false, subpage: '/login');

They are HTTP tests and run with the application's TestCase.

Option Default Description
languages ['en', 'cs'] The languages the switch offers; the switch tests are skipped for a single language.
demo false Expect the demo banner.
subpage '/login' A page one breadcrumb level below the homepage; null skips the check.
breadcrumb true false skips the breadcrumb tests, for a site designed without one.
Group What is tested
layout header, main and footer; the charset, viewport and CSRF meta tags; a title; <html lang>; one h1; the messages wrapper.
breadcrumb The last item is active; a subpage adds an item.
language switch Every language is offered and the current one highlighted; ?lang= switches the page and the next one keeps it.
error pages The error index; 401, 403, 404, 500 and 503 with their status and h1; 404 for an unknown code or page.
i18n pages /i18n and its subpages render.
vite config vite.config.js registers the dev watch plugin (see Vite); skipped without a vite.config.js.
demo mode The demo banner.

Service Providers

CommonServiceProvider

Auto-registered via package discovery. It provides:

  • Custom exception handler registration.
  • Loading of package routes, views (ig-common namespace), translations, and Blade components (ig namespace).
  • Registration of the Livewire Messages component.
  • Listener for mail logging (NotificationSent event).
  • Registration of the ulid32 validation rule.
  • Registration of all helper macros (String, Number, Carbon).
  • Automatic registration of all middleware into the web middleware group.
  • Queue connection safety check — throws an exception at boot if the queue connection is set to sync (except during unit tests).
  • SQLite defaults — every sqlite connection that leaves them unset gets busy_timeout 5000, journal_mode wal and transaction_mode IMMEDIATE (DEFERRED, the Laravel skeleton default, counts as unset), so concurrent writers wait for the lock instead of failing with database is locked. They are not applied while unit tests run. Set a value in the connection to keep your own, or IG_SQLITE_DEFAULTS=false to leave all of them alone.

ReadOnlyServiceProvider

Intercepts all write database queries and throws DbReadOnlyException when config('app.readonly') is true.

Read-only operations (SELECT, SHOW, DESCRIBE, EXPLAIN, PRAGMA) are always allowed. Queries targeting sessions, pin_logins, mail_logs, users, and socialites tables are whitelisted.

To use, register the provider in your config/app.php:

'providers' => ServiceProvider::defaultProviders()->merge([
    InternetGuru\LaravelCommon\ReadOnlyServiceProvider::class,
])->toArray(),

Then set readonly to true in config/app.php (or via environment variable) to activate read-only mode.

TranslationServiceProvider

Logs missing translations and translation variables in the current language. Throws an exception when not in production environment. In debug mode, checks all available languages.

  • Logs warning when a translation key is missing or a variable required in a translation string is not provided.
  • Checks all languages in debug mode from all available locales.
  • Throws exception InternetGuru\LaravelCommon\Exceptions\TranslatorException instead of logging when the app is not in production mode.

To use the provider, replace the default TranslationServiceProvider in config/app.php:

use Illuminate\Support\ServiceProvider;

'providers' => ServiceProvider::defaultProviders()->replace([
    Illuminate\Translation\TranslationServiceProvider::class => InternetGuru\LaravelCommon\TranslationServiceProvider::class,
])->toArray(),

Middleware

All middleware listed below is automatically registered in the web middleware group by the CommonServiceProvider. No manual registration is needed.

To bypass a specific middleware on a route, use the withoutMiddleware method:

Route::get('/example', ExampleController::class)
    ->withoutMiddleware(\InternetGuru\LaravelCommon\Http\Middleware\PreventDuplicateSubmissions::class);

CheckPostItemNames Middleware

Checks for invalid POST parameter names containing dots ".". Helps prevent issues with Laravel's input handling. Throws an exception in non-production environments and logs a warning in production.

Example:

  • When a POST request contains parameter names with dots:

    POST /submit-form
    Content-Type: application/x-www-form-urlencoded
    
    username=johndoe&user.email=johndoe@example.com
  • In Non-Production Environments: The middleware will throw an HTTP 400 exception:

    Invalid POST parameter names containing dots: user.email
    
  • In Production Environment: The middleware will log a warning:

    [WARNING] Invalid POST parameter names containing dots: user.email
    

InjectMetaRobots Middleware

Automatically injects a <meta name="robots"> tag into HTML responses before </head> when META_ROBOTS is set.

Set the following environment variable to enable:

Variable Description Default
META_ROBOTS Robots directive (e.g. noindex, noindex,nofollow). null (disabled)

Example .env:

META_ROBOTS=noindex,nofollow

The injected tag:

<meta name="robots" content="noindex,nofollow"/>

InjectUmamiScript Middleware

Automatically injects the Umami analytics tracking script into HTML responses when UMAMI_WEBSITE_ID is set.

The script is injected before the closing </head> tag. Set the following environment variables to enable:

Variable Description Default
UMAMI_WEBSITE_ID Your Umami website ID (required to enable tracking). '' (disabled)
UMAMI_SRC URL to the Umami tracking script. https://umami.internetguru.io/script.js
UMAMI_IDENTIFY Send user identity data (id, user_type, optional user_role) on page load. true
UMAMI_IDENTIFY_HASH Hash the user ID with SHA-256 before sending. false

Example .env:

UMAMI_WEBSITE_ID=0d38f931-afdc-4a99-a913-5c601fc95629

The injected script:

<script defer src="https://umami.internetguru.io/script.js" data-website-id="0d38f931-afdc-4a99-a913-5c601fc95629"></script>

LogRequest Middleware

Logs Incoming request at the debug level for every request except GETs, when turned on with IG_LOG_REQUESTS=true. Livewire requests that only refresh components (polls, refreshes on focus) are not logged.

It is off by default: the line carries no request input, so it repeats the web server's access log. Log what happened instead, as an audit line such as Log::info('Order paid', ['order' => $order->id]). An application that has its own copy of this middleware should remove it.

PreventDuplicateSubmissions Middleware

Prevents duplicate POST form submissions by caching a hashed request fingerprint (IP + path + input minus reCAPTCHA) for 1 minute. Livewire update requests are excluded.

When a duplicate submission is detected, the user is redirected back with input and an error message.

ReportImageProblems Middleware

Checks every <img> on an HTML page for both dimensions and an alt.

Problem Severity Log level
a local photo (jpg, png, webp, gif, avif) not served by laravel-images critical error
width or height missing severe warning
alt missing medium notice
alt="" low info
  • Each page logs one Image problems line with its URL and the problems per image src, at the level of the most severe. The same problems on the same page are logged at most once a day.
  • In debug mode the images are also outlined: critical double red, severe solid red, medium solid orange, low dotted orange. Hovering one shows its problems unless it has a title of its own.
  • An attribute bound in the browser (:alt, x-bind:width) counts as present.
  • The critical check runs only where laravel-images is installed. It covers photos bundled by Vite (Vite::asset()) too, and skips SVGs, other hosts and data: URIs.
  • /image-check shows one image of each kind, as a quick look at the outlines.
  • Turn it off with IG_IMAGE_WARNINGS=false.

SetPrevPage Middleware

Tracks the current and previous page URLs in the session for GET requests. Used internally by the exception handler to redirect users back to meaningful pages on errors.

Ignores AJAX requests and image (img/*) requests. Prevents tracking the same URL consecutively.

TimezoneMiddleware

Detects the user's timezone via IP geolocation and stores it in the session as display_timezone.

Uses the GeolocationService to resolve the IP address. Falls back to config('geoip.default_location.timezone') on failure. Resolves only once per session.

VerifyCsrfToken

Extends Laravel's CSRF verification with HMAC-based request signature verification. Requests containing a valid X-Signature and X-Timestamp header pair bypass CSRF checks. Livewire routes are also excluded by default.

The signature is validated using the app key with a 60-second freshness window.

Sanitization

Normalizes input before it is validated, driven by what a value is rather than by where it was submitted from. One registration covers controllers, Livewire components and bare validator() calls - no per-call-site opt-in, and no Form Requests required.

Both $request->validate() and a Livewire component's $this->validate() reach Illuminate\Validation\Factory::resolve(), and the CommonServiceProvider claims its resolver. Everything below follows from that single hook.

// Controller - the e-mail is normalized in the validated array *and* in the request
$validated = $request->validate(['email' => 'required|email']);
$validated['email'];        // "foo@example.com"
$request->input('email');   // "foo@example.com"
// Livewire - the property itself is rewritten, which is what the component reads next
public string $email = '  Fóo@Example.COM  ';

$this->validate(['email' => 'required|email']);

$this->email;               // "foo@example.com"

How a value is typed

Configuration lives in config/ig-common.php under sanitize, in two maps:

  • pipelines names sequences of operations. A bare pipeline name used inside another pipeline expands in place, so base composes into the rest.
  • types says what a value is. A key is either a field name (exact or a glob such as *_email) or a validation rule name / rule class FQN (numeric, Ulid32::class). Its value is always a pipeline name.

Resolution order for each string value, first match wins:

  1. sanitize.except - untouched, and never reported
  2. a map passed at the call site, or declared earlier in the request by the SanitizesInput trait
  3. types matched as a field name
  4. types matched as a validation rule
  5. nothing matched - see Unmapped input

Field names are matched segment by segment, from the deepest outwards, so the innermost name that means something wins: items.3.to_email is typed by to_email, while recipients.jan@example.com falls back to recipients because its own key is an address rather than a name. Each segment is normalized with Str::snake() and lowercased, so one entry covers the camelCase spelling Livewire properties use and the snake_case one request fields use: toEmail, to_email and items.0.to_email all match *_email.

Names are matched before rules because a name is usually more specific - last_name and note are both string|max:255, and only the name separates a person's name from free text.

What is never touched

  • sanitize.except - matched on the whole path or on any segment, so password also covers user.password. It ships with the password fields plus _token, _method, _previous and g-recaptcha-response: machine-generated values that carry a signature or address the framework itself, where normalizing can only break them.
  • sanitize.except_paths - whole requests, as path patterns for $request->is(). It ships with _debugbar/*: the debugbar validates its own machine values, such as ?type=js for its scripts, and reporting them as unmapped would keep it from loading.
  • #[Locked] Livewire properties - a locked property cannot be written by the client, so it holds what the server put there. Sanitizing it would rewrite the application's own configuration, and reporting it would bury the fields that really do come from a form. laravel-model-browser alone carries sixteen locked properties against four writable ones.
  • Anything that is not a string - arrays are walked into, and everything else passes through.

Operations

Operation Effect
trim Str::trim() - unicode-aware, unlike trim().
strip_invisible Drops C0/C1 control characters (keeping tab and newline), zero-width characters, the BOM, the soft hyphen, and the U+202A-U+202E bidi overrides used for display spoofing.
normalize_newlines CRLF/CR to LF, and runs of blank lines to one.
collapse_spaces Runs of horizontal whitespace to one space, and horizontal whitespace next to a newline dropped. Line breaks survive.
squish Str::squish() - collapses all whitespace including newlines, then trims. For values known to be single-line.
lower / upper Str::lower() / Str::upper().
ascii Folds to ASCII with ICU's Any-Latin; Latin-ASCII when the intl extension is available, falling back to Str::ascii().
digits Keeps 0-9.
keep:<class> / strip:<class> Whitelist / blacklist by character class; the text after : is spliced into /[…]/u. A slash in the class does not need escaping.
normalize_list Comma-separated value to one space after each comma, empty entries dropped.
max:<n> Hard cut at <n> characters.
nullify Empty string to null - the ConvertEmptyStringsToNull equivalent Livewire never gets.

Anything else in a pipeline is treated as a callable or an invokable class resolved from the container, which is how an app adds behaviour without registering anything.

Two rules the built-in pipelines follow, worth keeping when adding your own:

  • Normalize, do not strip character sets. Stripping characters can turn invalid input into valid input and quietly defeat the rule that follows. strip:\s, lower/upper and ascii are safe under that test; keep: is not, so only ulid32 and subdomain use it - values transcribed by hand, where dropping what the user typed around them is the point.
  • Collapse horizontal whitespace, not line breaks. base deliberately leaves newlines alone so a textarea keeps its paragraphs. Pipelines for values known to be single-line add squish themselves.

Adding your own type

// config/ig-common.php
'sanitize' => [
    'pipelines' => [
        'account_number' => ['base', 'strip:\s', 'upper'],
        'tel' => ['base', App\Sanitizers\PhoneNumber::class],
    ],

    'types' => [
        'account_number' => 'account_number',
        '*_account' => 'account_number',
        'mobile' => 'tel',
    ],
],

Unmapped input

There is no silent fallback: a string that resolves to no pipeline is reported rather than passed through, because a fallback nobody sees is a coverage gap nobody fixes.

  • While debugging (APP_DEBUG=true), an UnmappedInputException is thrown naming the field and the ways to declare it.
  • Otherwise, the strict pipeline runs and the key is logged once per request, so the request still succeeds and the gap stays findable.

Set IG_SANITIZE_STRICT=false to warn instead of throwing - useful for a staged rollout on an application that has not declared its fields yet. IG_SANITIZE=false disables sanitization entirely.

Request Macros

Macro Description
$request->sanitizedData($rules = [], $map = []) Returns the sanitized input array without validating and without modifying the request. For a controller that reads $request->input() rather than the validated array.
$request->sanitize($rules = [], $map = []) Merges the sanitized values into the request in place.

Request::validate() and Request::validateWithBag() are also overridden to sanitize first, so the request itself carries the normalized values after validating.

SanitizesInput Trait

Lets a Livewire component name the pipeline for properties whose type cannot be read from the configuration.

Most properties need nothing - the resolver types them by name or by their validation rules. A dynamic form is the exception: when properties are built as formData.0 … formData.N, the name carries no meaning and the rules are generic, so only the component knows what each field holds.

Declare the types in sanitizeTypes() and read the result of validate():

use InternetGuru\LaravelCommon\Traits\SanitizesInput;

class Feedback extends Component
{
    use SanitizesInput;

    public array $formData = [];

    protected function sanitizeTypes(): array
    {
        return [
            'formData.0' => 'email',
            'formData.1' => 'text',
        ];
    }

    public function send(): void
    {
        $data = $this->validate($rules);

        $data['formData'][0];   // "foo@example.com"
        $this->formData[0];     // "  Fóo@Example.COM  " - as it was typed
    }
}

The trait hooks Livewire's own prepareForValidation(), so the cleaning happens on the way into both validate() and validateOnly() with nothing to call. The declaration also reaches the validator resolver for the rest of the request, so a property typed this way is not then reported as unmapped.

The properties themselves are left alone, which is why the component reads what validate() returned. Rewriting a field mid-edit - when validation has just failed on some other field - is a surprise nobody asked for, and the person keeps seeing what they typed. A component that would rather have the cleaned value on the property can leave sanitizeTypes() empty and let the resolver write it back instead, which is what happens for every property the configuration can already type.

Both methods are protected on purpose: Livewire exposes a component's public methods to the client, and these decide what gets written where.

A package or an application can declare types for its own fields from a service provider, which is how laravel-user, laravel-feedback and laravel-model-browser cover theirs:

$types = $this->app['config']->get('ig-common.sanitize.types');

if (is_array($types)) {
    $this->app['config']->set('ig-common.sanitize.types', [
        'register' => 'flag',
        'remember' => 'flag',
        ...$types,   // entries the application already set win
    ]);
}

Notes

  • Validator::resolver() holds one closure. An application that registers its own resolver after this package boots silently replaces this one and disables sanitization.
  • Request::validate() mirrors framework internals. The override copies the body Laravel registers in FoundationServiceProvider::registerRequestValidation(), including its Precognition handling, because there is no public accessor for an existing macro. Keep it in sync when upgrading the framework.
  • Lowercasing e-mail changes lookups. On a database with a case-sensitive collation, a user stored as Foo@Example.com will no longer be found by a login form that now sends foo@example.com. Normalize existing rows before enabling this on an application with such data.

Helper Methods

The Helpers class provides useful static methods for Laravel applications.

Configuration and example usage:

  1. Add the following lines to config/app.php:

    use Illuminate\Support\Facades\Facade;
    
    'aliases' => Facade::defaultAliases()->merge([
        'Helpers' => InternetGuru\LaravelCommon\Support\Helpers::class,
    ])->toArray(),
  2. Use Helpers class methods in your application:

    <meta name="generator" content="{{ Helpers::getAppInfo() }}"/>

Available methods:

Method Description
getAppInfoArray() Returns app name, environment, version, git branch, and commit as an array.
getAppInfo() Returns app info as a single string.
parseUrlPath($homeRoute, $skipFirst) Parses the current URL path into breadcrumb segments with translations.
createTitle($separator, $homeRoute) Generates a page title from breadcrumb segments (reversed, separated).
getEmailClientLink() Returns a link to the Mailpit inbox when using Mailpit mailer.
verifyRequestSignature(Request $request) Verifies HMAC-SHA256 request signature (X-Signature + X-Timestamp headers).

For full implementation details, see the Helpers class.

Helper Macros

The package registers a set of useful macros for Str, Carbon, and Number. See macros.php for the complete list.

String Macros

Macro Description
Str::ref($length) Generates a random alphanumeric reference code (excludes ambiguous characters i, l, o, 0, 1, u). Starts with a letter and contains at least one digit.

Number Macros

Macro Description
Number::currencySymbol($in, $locale) The symbol of a currency as the locale writes it. Defaults to Number::defaultCurrency() and Number::defaultLocale().

Number::defaultLocale() follows the application's locale: the package sets it on boot and on every app()->setLocale(), so Number::format(), Number::currency() and the other Number methods format in the current language.

Carbon Macros

Macro Description
$date->dateForHumans() Locale-aware date (L format).
$date->dateTimeForHumans() Locale-aware date and time (L LT format).
$date->myDiffForHumans() Human-readable time difference with "just now" for <60 seconds and "1 year" normalization.
$date->timeForHumans() Clean time format (removes leading zeros and :00).
$date->toDisplayTimezone() Converts the date to the user's display timezone stored in the session (display_timezone), falling back to config('app.timezone').
$date->randomWorkTime($from, $to) Sets a random time during work hours (default 9–17).

Example usage:

use Carbon\Carbon;
use Illuminate\Support\Number;
use Illuminate\Support\Str;

echo Str::ref(6);
// Output: "k3mhpq"

Number::useCurrency('USD');
echo Number::currency(1234, precision: 0);
// Output (en locale): $1,234
echo Number::currencySymbol();
// Output (en locale): $
echo Number::currencySymbol('CZK', 'cs');
// Output: Kč

$date = Carbon::parse('2023-12-31');
echo $date->dateForHumans();
// Output (en_US locale): 12/31/2023
$dateTime = Carbon::parse('2023-12-31 18:30:00');
echo $dateTime->dateTimeForHumans();
// Output (en_US locale): 12/31/2023 6:30 PM

Blade Components

All Blade components are registered under the ig namespace and can be used with <x-ig::component-name />.

Breadcrumb Blade Component

Renders breadcrumb navigation based on routes matching the current URL segments. Supports translations with short and long labels, custom divider, and segment skipping. On a narrow screen the levels fold into a menu behind the first one.

Key Features:

  • Compact on a Phone – Below Bootstrap's sm breakpoint the breadcrumb is a dropdown toggle with the first item (or the mark) and an arrow, opening a menu of all levels drawn as stops on one line, the current page a filled one.

  • Home Mark – The mark attribute takes an image URL drawn beside the first item and as the menu toggle, e.g. a small logo.

  • Custom Items – The items attribute replaces the items parsed from the URL, as a list of ['uri' => …, 'translation' => …].

  • Customizable Divider – Allows a custom divider symbol between breadcrumb items.

  • Short and Long Labels – Using trans_choice if available shows n-th right translation based on the item position.

  • Segment Skipping – Skips a specified number of URL segments. Useful for nested routes or routes with prefixes (e.g. language).

  • Skip Prefixes – Routes whose URI starts with a configured prefix are treated as error pages (no breadcrumb generated), preventing missing translation warnings. Configured via breadcrumb_skip_prefixes in config/ig-common.php:

    'breadcrumb_skip_prefixes' => [
        '_debugbar',
        '_ignition',
        'livewire',
        'storage',
        'telescope',
        'horizon',
    ],

Usage:

<!-- By default, this will generate breadcrumb items based on the current URL path. -->
<x-ig::breadcrumb/>
<!-- You can change the divider symbol by setting the divider attribute -->
<x-ig::breadcrumb divider="|" />
<!-- If you need to skip certain segments of the URL (e.g., a language prefix), use the skipFirst attribute -->
<x-ig::breadcrumb :skipFirst="1" />
<!-- A small logo beside the first item and as the menu toggle on a phone -->
<x-ig::breadcrumb :mark="asset('logo-small.svg')" />

Styles come from ig::common/breadcrumb: the mark and the menu's line and stops. The size of the mark and the colours of the line and of the current stop are set by the $breadcrumb-* variables, which have to be given before the stylesheet is imported. The arrow of the toggle is the solid faAngleDown, which the application registers in Font Awesome. A mark given as a URL in Sass would be inlined by Vite and lose the custom property, which is why the component hands it over as --breadcrumb-home-mark.

Example:

  • Assuming you have the following routes defined:
    <?php
    Route::get('/', function () {
        // ...
    })->name('home');
    
    Route::get('/products', function () {
        // ...
    })->name('products.index');
    
    Route::get('/products/{product}', function ($product) {
        // ...
    })->name('products.show');
  • And your translation files (resources/lang/en/navig.php) include:
    <?php
    return [
        'home' => 'Long Application Name|LAN',
        'products.index' => 'All Products|Products',
        'products.show' => 'Product Details',
    ];
  • When you visit the /products/123 URL, the short translation will be used for the home and products.index routes.
    LAN > Products > Product Details
    
  • When you visit the /products URL, the short label will be used for the home route.
    LAN > All Products
    
  • When you visit the / URL, the long label will be used for the home route.
    Long Application Name
    

System Messages (Livewire Component)

Renders system temporary success messages and persistent error messages in different colors, with a close button. Powered by Livewire.

The component automatically picks up session success and errors data. You can also send messages dynamically via Livewire events.

Include the component in your Blade template:

<livewire:ig-messages />

Dispatching messages from other Livewire components:

$this->dispatch('ig-message', type: 'success', message: 'Item saved!');
$this->dispatch('ig-message', type: 'danger', message: 'Something went wrong.');

Known issue: with Laravel Debugbar enabled in an application that starts the session in its global middleware, a message flashed before a Livewire redirect does not show on the next page. Debugbar fetches the data of the Livewire request (_debugbar/open) while the browser is still on its way to the next page, and that request uses up the flash. Production without Debugbar is not affected. Locally, set DEBUGBAR_ENABLED=false to see the messages.

Form Blade Components

The package provides a set of Blade components for forms and various input types.

Notes:

  • The Google reCAPTCHA V3 service is enabled by default. To disable it, set the recaptcha attribute to false.
  • tooltip="…" on x-ig::input puts an info icon after the label, which shows the text in a tooltip on hover, focus or tap. The icon is an outlined question mark: the application initialises Bootstrap tooltips on [data-bs-toggle="tooltip"] and registers faCircleQuestion from @fortawesome/free-regular-svg-icons.
  • :defaultToday="true" on an empty type="date" input of x-ig::input shows today's date (in the display timezone). It has no effect with wire:model, where Livewire sets the value; fill the property instead.

Complete example:

<x-ig::form :action="route('test')" :recaptcha="false">
    <x-ig::input type="text" name="name" required>Name</x-ig::input>
    <x-ig::input type="email" name="email" tooltip="Used only to send the receipt.">Email</x-ig::input>
    <x-ig::input type="select" name="simple-options" :options="['a', 'b', 'c']">Simple Options</x-ig::input>
    <x-ig::input type="select" name="keyed-options" :options="['a' => 'Option A', 'b' => 'Option B']" useoptionkeys>Keyed Options</x-ig::input>
    <x-ig::input type="select" name="advanced-options" value="2" :options="[
        ['id' => '1', 'name' => 'User 1'],
        ['id' => '2', 'name' => 'User 2'],
        ['id' => '3', 'name' => 'User 3'],
    ]">Advanced Options</x-ig::input>
    <x-ig::input type="checkbox" name="checkbox" value="1">Checkbox</x-ig::input>
    <x-ig::input type="radio" name="radio" value="1">Radio</x-ig::input>
    <x-ig::input type="textarea" name="description">Description</x-ig::input>
    <x-ig::submit>Submit Form</x-ig::submit>
</x-ig::form>

Language Switch Blade Component

Renders a language switcher as a list of links with the current language highlighted.

<x-ig::lang-switch />

Print Button Blade Component

Renders a print button that triggers the browser's print dialog.

<x-ig::print-button />

Footer Copy Blade Component

Renders a copyright footer with provider information and year range.

<x-ig::footer-copy />
<x-ig::footer-copy icon="" />
<x-ig::footer-copy icon="fa-solid fa-fw fa-leaf" />
Prop Default Description
icon null null renders the bundled duotone seedling SVG, an empty string omits the icon, any other value is used as an icon class. The icon is coloured by the provider-ico class ($provider-ico-color).

Footer Blade Component

Renders the default application footer: page QR code, copy link, complaints form link, technical feedback form link, language switch and copyright.

<x-ig::footer />

Both feedback forms are laravel-feedback Livewire components declared by the footer itself, with the ids feedback-form and complaints-form. The technical feedback form is rendered whenever that package is installed and goes to the provider address; the complaints form additionally requires complaints-email to be set. Without the package the footer silently drops both forms and their links, everything else is rendered as usual.

Anything passed to the slot is rendered at the top of the footer, above the links. The component's own content is wrapped in a single div, so footer > div can be styled uniformly when the slot passes block elements too.

<x-ig::footer
    complaints-email="restaurant@example.com"
    :complaints-locations="['Restaurant Downtown', 'Restaurant Airport']"
>
    <ul class="list-inline">
        <li class="list-inline-item"><a href="https://www.facebook.com/example">Facebook</a></li>
    </ul>
</x-ig::footer>
Prop Default Description
feedback-email ig-common::layouts.provider.email Technical feedback recipient.
feedback-name ig-common::layouts.provider.name Technical feedback recipient name.
feedback-title ig-common::layouts.support.link Link text and modal title.
feedback-subject ig-common::layouts.support.subject Email subject.
feedback-description null Modal description, falls back to the feedback package default.
feedback-fields message, attachments, email Technical feedback field definitions, overrides the defaults entirely.
complaints-email null Complaints recipient; the form is omitted when not set.
complaints-name config('app.name') Complaints recipient name.
complaints-title ig-common::layouts.complaints.link Link text and modal title.
complaints-subject app name + title Email subject.
complaints-description null Modal description.
complaints-fields location, occurred_at, message, email Feedback field definitions, overrides the defaults entirely.
complaints-locations [] Location names rendered as a required select; the field is omitted when empty.
feedback-icon none Optional technical feedback link icon class.
complaints-icon none Optional complaints link icon class.
share true Render the share page link.
lang-switch true Render the language switch.
generated false Render the page generation time in the display timezone.

The location and occurred_at field definitions are registered into ig-feedback.names when laravel-feedback is installed, unless the application already defines them.

The technical feedback form declares an optional attachments field, so users can attach screenshots of what went wrong (up to 3 images or PDFs, 5 MB each). Limits and accepted types are configurable under ig-feedback.names.attachments, and feedback-fields replaces the field set altogether.

Modal Blade Component

Renders a Bootstrap modal whose markup is on the page from the start and only hidden, so it can be shown without a server round trip.

<x-ig::modal id="my-modal" title="My title">Body</x-ig::modal>
<a href="javascript:void(0)" onclick="window.igModal.open('my-modal')">Open</a>
Prop Default Description
id slug of the title Wrapper id, passed to window.igModal to open and close it.
title null Modal title, next to the close button.
open false Render it visible right away.
centered false Vertically centre the dialog.
hash null URL fragment opening the modal on page load; the fragment then follows it.
wire-open null Livewire property mirroring the open state, kept in sync so a re-render does not close the modal.

Additional attributes are merged onto the wrapper. The wrapper carries the ig-modal class and is hidden with d-none; window.igModal.open(id), close(id) and closeAll() toggle it, the escape key and a click on the backdrop close it. Every modal registers itself and is watched for class changes, so a Livewire re-render that opens or closes it is handled the same way as a click; opening and closing emit the bubbling ig-modal-opened and ig-modal-closed events. The helper is a small inline script, free of Alpine.js and Livewire, so the modal responds to the first click without waiting for a bundle to load.

An open modal follows the visual viewport. iOS positions fixed elements against the layout viewport, so once the page is zoomed — a pinch, or Safari zooming in on a focused field — a plain Bootstrap modal covers only part of what the reader can see and sits shifted up the screen. window.igModal.syncViewport() writes the visible area into the --ig-modal-top, --ig-modal-left, --ig-modal-width and --ig-modal-height custom properties, which the dialog and the backdrop are sized and placed by; it runs whenever a modal opens or closes and on every visualViewport resize and scroll. Browsers without visualViewport leave the properties unset and fall back to the Bootstrap defaults.

Share Page Blade Component

Renders a link that opens a modal with a QR code of the current page URL, a copy button and the full URL below it, so the page can be opened on a phone or passed on.

<x-ig::share-page />
<x-ig::share-page url="https://example.com/menu" title="Share the menu" :size="320">Menu QR</x-ig::share-page>
Prop Default Description
url current URL Encoded and shared content.
title ig-common::layouts.share.title Modal title.
icon fa-regular fa-fw fa-share-from-square Link icon class, pass an empty string to omit.
size 240 SVG size in pixels.
id slug of the title Modal id, also the URL fragment opening it.

Links with an icon get the link-ico class, which positions the icon outside the link box so the link underline runs under the text only. The QR code is rendered server-side as an inline SVG, and the modal is the modal component, so it opens on the first click without waiting for a bundle to load, and linking to #share-page opens it on page load. The copy URL button copies the URL to the clipboard, and the URL below it wraps over as many lines as it needs.

Copy URL Blade Component

Renders a link that copies the current page URL to the clipboard, confirming with a check icon for two seconds.

<x-ig::copy-url />
<x-ig::copy-url url="https://example.com/menu">Copy the menu link</x-ig::copy-url>
Prop Default Description
url current URL Copied value and href fallback.
icon fa-regular fa-fw fa-copy Idle icon class, pass an empty string to omit both icons.
copied-icon fa-solid fa-fw fa-check Icon shown for two seconds after copying.

Clipboard access requires a secure context (HTTPS or localhost); when it is unavailable the failure is reported as an error message.

Card Blade Component

Renders a card: an optional row of chips, a heading, a subtitle and free content, optionally turning its whole surface into a link.

<x-ig::card title="Reduced balls and dual graphs" subtitle="Prague, 2026">
    <p>Content of the card.</p>
</x-ig::card>

<x-ig::card
    title="Higher-dimensional chordality"
    badge="Preprint"
    badge-type="preprint"
    link="https://example.com/paper"
    link-label="Read the paper"
/>

<x-ig::card title="What we do" gray />
Prop Default Description
title – Card heading.
level 4 Heading level of the title, so a card keeps the outline of the page it sits on.
subtitle – A line of context below the heading, rendered as p.lead.
badge – Text of the chip above the heading, or an array of several.
badge-type – Kind of chip, added as the badge-{type} class, which colours its dot.
link – Makes the whole card follow this link.
link-label ig-common::layouts.card.open Accessible name of the link, since the button itself is only an icon.
icon fa-solid fa-arrow-up-right-from-square Icon of the corner link button.
gray false Puts the card on a grey surface, with its heading and content centred.

Styles come from ig::common/card. A badge is drawn as the same chip as a label, so the $ig-label-* variables style both. The dot colour per badge kind is taken from the $card-badge-dots map, keyed by badge-type, which is empty by default:

$card-badge-dots: (
    preprint: $orange,
    article: $green,
    thesis: $indigo,
);

@import 'ig::common/card';

Two content classes are styled for use inside the slot: card-image for a full-bleed picture reaching over the card's padding, and card-list for a list of what the card holds. An actions element is pushed to the foot of the card, so buttons line up across cards of unequal height.

Card Row Blade Component

Groups cards into a sideways scrolling carousel with paging arrows, or into a grid wrapping onto as many lines as needed.

<x-ig::card-row label="Publications">
    <x-ig::card title="First" />
    <x-ig::card title="Second" />
</x-ig::card-row>

<x-ig::card-row label="Research directions" layout="grid" size="narrow" tinted centered>
    <x-ig::card title="First" />
</x-ig::card-row>
Prop Default Description
label ig-common::layouts.card_row.label Accessible name of the group of cards.
layout carousel carousel scrolls sideways with arrows, grid wraps onto as many lines as needed.
size – In the grid layout, narrow fits four cards to a line and wide two; omit for three.
tinted false Tints each card with a colour derived from the label.
centered false Centres the cards instead of pinning them to the left edge.

Styles come from ig::common/card-row; the carousel needs the cardRow Alpine.js component, which ig::common-js registers. Each card is a direct child of the row, or sits in an element of the application's own that is, such as an item drawing a timeline above its card; the application sizes such an item as the row sizes a card, and the keys, drag handles and snapping work by the items either way. When the carousel overflows, a handle (the solid faEllipsisVertical icon, which the application registers) sits between neighbouring cards for a mouse to drag the row by; touch devices swipe instead and do not show it. The left and right keys step focus card by card through the carousel holding focus, or else the one on screen whose middle is nearest the middle of the screen, paging the row when the next card is out of view; the focused card rises onto a deeper shadow ($card-row-card-lift, $card-row-card-lift-shadow) and Enter follows its link. The keys are left alone in form fields, with a modifier held and while a modal is open. The row's gap, the widths its cards settle at and the look of the paging buttons are set by the $card-row-* variables, which have to be given before the stylesheet is imported. A carousel scrolls sideways, so its track clips downwards too — $card-row-bleed is the room the cards' shadows get inside it, and a card with a deeper shadow than the default needs it raised.

The tints are derived from the label, so a row keeps the same palette across requests while different rows get different colours. The palette repeats every eight cards, and neighbouring cards - including the wrap from the eighth back to the first - always sit about 135 degrees apart on the colour wheel.

Tag Cloud Blade Component

Shows a list of terms as coloured chips, or as a typographic word cloud whose lines are fitted to the width they have.

<x-ig::tag-cloud :tags="['Research', 'Teaching', 'Awards']" />

<x-ig::tag-cloud typography tags="Research, Teaching, Awards" />
Prop Default Description
tags [] The terms to show, as a list of strings or a comma separated string.
typography false Draws the terms as plain coloured words of varying size, not as chips.

Hues are spread by the golden angle, so neighbouring tags never land on a similar colour however many there are.

Styles come from ig::common/tag-cloud; the chips are labels, and the word cloud is set by the $tag-cloud-* variables, which have to be given before the stylesheet is imported. A cloud sitting on a card is usually given a negative inline margin through $tag-cloud-margin, so it reaches past the card's padding and reads as its own shape rather than as a block of text.

The typographic cloud needs the tagCloud Alpine.js component, which ig::common-js registers: its sizes are measured in the browser, since every line is packed and then scaled to fill the width of the cloud exactly. The cloud stays hidden until it has been measured, so the fallback sizes rendered server-side never show; without JavaScript those sizes are what is shown.

Label Blade Component

Names one value out of a set - a status, a role, a payment type, a branch - as a chip read in plain text on white, with the value carried by a small colored dot.

A label is colored in one of three ways:

  • Specific color: a theme variant or a color of your own, for a value with a fixed meaning.
  • Registered group: a list of keys registered once, for values from the database or a plain list.
  • Enum: the cases of an enum, with no registration.

In a group or an enum, a value has one color on every page, and no two values share one.

A label given none of these, or given a color, variant, group or key that is not valid, throws a LabelException in debug mode. Otherwise it logs a warning and shows a gray dot, as a missing translation is handled. An invalid value is never passed over for the next one, so a typo can't show as some other color.

Prop Default Used by Description
text null all The label itself. The slot is used instead when one is given.
variant null specific color Kind of value, drawn in its palette tone: primary, secondary, success, danger, warning, info, light or dark. info, success, warning and danger take the color of the notice of the same type where ig::common/label is loaded.
color null specific color An explicit color in hex, rgb(), hsl(), oklch() or var() notation. It takes precedence over the variant.
group null group, enum A group registered in LabelGroups, or an enum class using RendersLabel.
key null group, enum The value within its group, which picks its color. An enum case stands for its name.
icon null all Font Awesome classes of an icon shown in place of the dot.
slim false all Cuts the padding down, for a label read inside a line of text rather than in a column of its own.

Other attributes, such as class, id or data-*, are passed on to the chip.

Specific color

<x-ig::label text="Paid" variant="success" />

<x-ig::label text="VIP" color="#b8860b" />

<x-ig::label text="Administrator" variant="danger" icon="fa-solid fa-user-gear" />

<x-ig::label text="Hidden" variant="secondary" slim />

A variant names the kind of value and draws it in that tone of the palette: green for success, red for danger, and so on. A color sets the dot to any color and takes precedence over the variant.

Registered group

// app/Providers/AppServiceProvider.php
use InternetGuru\LaravelCommon\Support\LabelGroups;

public function boot(): void
{
    LabelGroups::register('payment-types', ['register', 'gateway', 'manual', 'bank']);

    LabelGroups::register(
        'locations',
        fn () => Location::orderBy('id')->pluck('code'),
        forced: ['ost' => 5],
        seed: 40,
    );
}
<x-ig::label :text="$location->name" group="locations" :key="$location->code" />

Register each group of your own once, in a service provider's boot(), so it exists before any view renders it. Each key takes the palette color of its place in the list.

  • Keys are an array, or a closure returning any iterable. A closure is read when the group is first used in a request and kept for the rest of it, so a request showing no such label runs no query.
  • Keep the order stable, by id or a fixed list, not by name. A key added at the end leaves the others their colors.
  • forced gives a key a slot by hand; the key that slot was taken from moves to the next free one, and forcing one past the end drops the color left over.
  • seed turns the palette, so different groups start from different colors: a string is hashed, an integer is the angle in degrees. It defaults to the name of the group.
  • Registering a name again replaces the group, so an application can override one a package registers.

Enum

enum OrderStatus: string implements HasLabel
{
    use RendersLabel;

    case PAID = 'paid';
    case UNPAID = 'unpaid';

    public function label(): string
    {
        return match ($this) {
            self::PAID => __('order.status.paid'),
            self::UNPAID => __('order.status.unpaid'),
        };
    }

    public function variant(): ?string
    {
        return match ($this) {
            self::PAID => 'success',
            self::UNPAID => 'danger',
        };
    }
}
{!! $order->status->toLabelHtml() !!}

<x-ig::label :text="$channel->label()" :group="Channel::class" :key="$channel" />

An enum implementing the HasLabel contract with the RendersLabel trait renders each case with toLabelHtml(), taking the same slim flag. It draws a case in its variant(), in a color of its own, or in the palette color of the enum, so it shows a case whatever colors its enum uses.

The enum class is also a label group, with no registration: LabelGroups recognizes it when it is first used. Its keys are the names of the cases whose variant() is null, in the order they are declared; cases with a variant are not in it. For an enum like that, <x-ig::label> with the class as the group gives the same chip as toLabelHtml(). A group registered under the class name overrides it.

Override these methods of the trait to change how cases are shown:

  • labelColor(): a palette slot (an integer) or a color of its own (a string) for a case.
  • labelPaletteSeed(): what turns the palette of the enum; the class name by default.
  • labelIcon(): Font Awesome classes of an icon shown in place of the dot.

A HasLabel value that is not an enum has no set to share, so without a variant() or a labelColor() it fails as a label does.

Palette, PHP and styles

Colors come from InternetGuru\LaravelCommon\Support\Palette: one mild tone, each color at least 3:1 against white; the danger variant alone is a full red. Slot n always has the same color, whatever the size of the group, and the first slots are the furthest apart; after eight, a darker ring follows.

Label::html() takes the same arguments as the component and returns the chip as HTML, for the places building their HTML in PHP, such as a model browser column formatter. It passes on no other attributes.

Styles come from ig::common/label. Labels, card badges and tag cloud chips are one chip, styled by the $ig-label-* variables given before the stylesheets are imported:

  • black text on white, with the kind of value carried by the dot
  • 1rem wherever it stands, in a heading or in a table alike, set by $ig-label-font-size
  • the dot, sized by $ig-label-dot-size, sits $ig-label-dot-lift above the middle of the line and glows softly in its color, set by $ig-label-dot-glow-*
  • a slim label never makes its line of text taller, and its text sits on the baseline of the words around it
  • the border glows in the dot color at the bottom right corner and faintly at the top left, set by $ig-label-accent-*
  • one line, with a text too long for its place cut short; $ig-label-wrap: true lets it wrap instead

Page Heading Blade Component

Renders the page heading with a remark about the page, such as a list showing only some records.

<x-ig::page-heading :heading="__('order.list')" badge="Restricted" variant="warning">
    You are viewing your own orders.
</x-ig::page-heading>
Attribute Default Description
heading required The text of the h1, escaped; pass an HtmlString to keep markup. Other attributes go on the h1.
badge null A label above the heading. The slot becomes its tooltip.
variant null info, success, warning or danger. It colors the badge (info when empty) and gives the remark below the heading its icon; without it, that remark is plain text.
icon null Font Awesome classes that replace the variant's icon on the badge.
tooltip true With a badge, the slot is its tooltip; false writes the slot below the heading instead, for a remark that must be read.
description-variant variant The variant of the remark below the heading, when it should differ from the badge's, e.g. a warning status with advice in info.
  • With a badge, the slot is its tooltip, and nothing is written below the heading.
  • A badge slot (<x-slot:badge>) stands above the heading in place of the label, for a badge of your own such as a live status; it carries its own explanation, so the default slot is not shown unless tooltip is false.
  • Without a badge, the slot follows the heading as a remark, with the variant's icon when a variant is given, or nothing when the slot is empty.
  • Register the solid faCircleInfo, faCircleCheck and faTriangleExclamation icons; warning and danger share the triangle. The application initializes Bootstrap tooltips.
  • Styles come from ig::common/page-heading.

Demo Info Blade Component

Renders a demo mode warning banner informing users that displayed information is illustrative and may reset.

<x-ig::demo-info />

Read-Only Mode Info Blade Component

Renders an informational banner indicating the application is in read-only mode and editing is disabled.

<x-ig::read-only-mode-info />

Notice Styles

Styles the full-width notices above the page header as an icon and a short centred line of text, with no background, border or shadow.

The demo and read-only banners above, and laravel-user's system message and app hints, render as div.container-fluid.alert.alert-{type} > p and look like Bootstrap's alert bars by default. Import the partial to restyle them:

$notice-max-width: 30em;

@import 'ig::common/notice';

The types info, success, warning and danger each get an icon (circle-info, circle-check, and triangle-exclamation for both warning and danger) and a colour, set by $notice-{type}-color and $notice-{type}-icon. The icons are drawn in CSS, so they need no Font Awesome registration. The other $notice-* variables set the column width, the icon width and the text and link colours; give them before the stylesheet is imported.

Email Feedback Blade Component

Renders a technical support email link with pre-filled subject and diagnostic data.

<x-ig::email-feedback />

Editable Blade Component

Provides an Alpine.js editable data component for inline editing functionality.

<x-ig::editable />

Admin Button Text Blade Component

Renders a slot for button text that is replaced with a configurable admin label when the authenticated user is an admin.

<x-ig::admin-button-text>Save</x-ig::admin-button-text>

When auth()->user()->isAdmin() is true, the slot content is replaced with the ig-common::layouts.submit-admin translation string.

Association History Blade Component

Renders a chronological edit history for a model, grouped by author and 10-minute time windows. Requires the AssociationHistory trait on the model.

Setup:

  1. Publish and run the migration:

    php artisan vendor:publish --tag=ig-common:migrations
    php artisan migrate
  2. Add the trait and declare which fields to track:

    use InternetGuru\LaravelCommon\Traits\AssociationHistory;
    
    class Reservation extends Model
    {
        use AssociationHistory;
    
        protected array $associationHistoryTracked = ['status', 'note'];
    }
  3. Optionally configure column label and label value translations in config/ig-common.php:

    'association_history' => [
        'columns' => [
            \App\Models\Reservation::class => 'reservation.history.column',
        ],
    ],

    With corresponding translation keys like reservation.history.column.status, reservation.history.column.status.pending, reservation.history.column.status.confirmed and reservation.history.column.note.

  4. Render the component:

    <x-ig::association-history :model="$reservation" />

    Optional :limit attribute (default 10) controls how many entries are loaded.

The component derives the "new value" for each entry from the current model state and automatically reads the created_by field (override via $associationHistoryCreatedBy) to prepend a creation entry.

Component Signatures Blade Component

Renders an HTML comment listing all installed internetguru/* package names and versions. Only active in debug mode.

<x-ig::component-signatures />

Casts

CarbonIntervalCast

Casts a string to a CarbonInterval and back. Uses CarbonInterval::fromString() to parse and forHumans() (in English locale) to serialize.

use Illuminate\Database\Eloquent\Model;
use InternetGuru\LaravelCommon\Casts\CarbonIntervalCast;

class Task extends Model
{
    protected $casts = [
        'duration' => CarbonIntervalCast::class,
    ];
}

Keeping Pages Current

A page often shows data that others change while it is open. Polling with wire:poll re-renders and morphs the component on every tick even when nothing changed, which costs a render and swaps every Font Awesome icon in it, so the icons flicker. The watcher asks instead: a cheap fingerprint of what is shown is compared on a shared clock, and only a change does anything on the page.

One clock serves every watcher on the page. Watchers with the same interval check on the same wall-clock seconds, so Livewire bundles their calls into one request. A tab that is hidden checks ten times less often and catches up when it is shown, when the window gets focus, and when the page returns from the back/forward cache. A failed check never replaces the page:

Failure What happens
offline no checks; a toast says the page is not being updated, and it hides and checks at once when the browser is back online
network error, timeout, 5xx, 429 retried after 15 s, 30 s, 1 min, 2 min and then every 5 min, back to the normal interval after the first success
419, 401, 403, or a redirect the session expired or the user was signed out; all watchers stop and a toast with a Reload button stays
404, 410 what the page shows is gone; all watchers stop and the "updated" toast with a Reload button stays

These messages are warning toasts that look like every other toast. The browser builds them from a template in <livewire:ig-messages />, since they report the very moments a request fails, so a page without that component shows none. Only one shows at a time, and the newer state replaces the older, except that going offline never replaces a toast with Reload. Each closes with its ×; a closed Reload toast stays closed, and the offline one comes back on the next disconnect. A page without a watcher shows the offline toast too, saying links and forms work again once back online.

The package's Livewire error handler leaves failed watch checks alone. An application with a Livewire request hook of its own skips them the same way:

Livewire.hook('request', ({ payload, fail }) => {
    fail(({ preventDefault }) => {
        if (window.igWatch?.isWatchRequest(payload)) {
            return;
        }
        // …
    });
});

A push or any other script can ask every watcher to check at once with window.dispatchEvent(new Event('ig-watch:check')). When the watching stops (a found page change or a notice), ig-watch:stopped is dispatched on window, so an application's own background timer can stop too.

When the user asked for fresh data, e.g. with a refresh button, call window.igWatch.allowReload(20): for that many seconds a change the page watcher finds reloads the page even while the user moves or has scrolled, as long as nothing is being edited.

An application's own background calls (e.g. a sync status) can fail as quietly: register their method names with window.igWatch.addWatchMethods('syncStatus'). Use names distinctive enough not to match a user action, since the rule holds for every component on the page. A typed value that rides along with a check, also of another component, counts with it, so its failure is quiet and retried.

A watched page whose sources cannot be rebuilt the same way in a later request (e.g. a model loaded with a partial select) would look changed on every check. The page watcher then reloads once and shows the notice instead of reloading again.

WatchesForChanges Trait

For a Livewire component that draws everything that can change. It refreshes in place, in one request: an unchanged fingerprint skips the render, so no markup is sent; a changed one renders the component as usual.

use InternetGuru\LaravelCommon\Traits\WatchesForChanges;

class PendingReservations extends Component
{
    use WatchesForChanges;

    protected function watchFingerprint(): string
    {
        return md5(json_encode($this->items()));
    }
}
<div>
    <x-ig::watch :interval="15" />
    …
</div>
  • The fingerprint must cover everything the view shows, including what changes with time alone, such as a status that turns expired. It is read once per request and stored on every render.
  • Override watchChanged() to update state before the render a found change causes.
  • Place x-ig::watch inside the component's root element. The default interval is 15 seconds.

Page Watch

For a page not drawn by one Livewire component, such as an order detail rendered by a controller. Register what the page shows, from the controller or the view:

use InternetGuru\LaravelCommon\Support\WatchedPage;

WatchedPage::add($order, ...$order->vouchers);
WatchedPage::add([PaymentState::class, 'forOrder', [$order->id]]);
WatchedPage::message(__('order.paid'));

and place the watcher once in the layout:

<x-ig::page-watch />

It renders nothing on a page that registered nothing.

  • A source must be rebuildable in a later request, so a model (by class, key and updated_at) or a static [Class::class, 'method', [scalar arguments]] callable. A closure is refused, and a deleted model counts as a change.
  • A model implementing InternetGuru\LaravelCommon\Contracts\HasPageFingerprint adds pageFingerprint(), for a state that changes with time alone and leaves updated_at as it is.
  • On a change, the page reloads only if nothing is being edited (no unsaved field, open modal or dropdown, selected text, or pending Livewire change), the page is scrolled to the top and there was no mouse or key activity for 3 seconds. Otherwise a toast with a Reload button stays and watching stops. After a reload, the message (or the default "This page has been updated.") is flashed.

Unchanged Icons

Font Awesome replaces each <i> with an <svg>, so every morph swaps every icon. keepUnchangedIcons() switches Font Awesome to its nest mode, where the <i> stays and holds the <svg>, and lets the morph skip each icon whose markup did not change; a changed one is reset and converted again.

import { config, dom, library } from '@fortawesome/fontawesome-svg-core';
import keepUnchangedIcons from 'ig::common-js/keep-unchanged-icons';

library.add(/* … */);
keepUnchangedIcons({ config, dom });
dom.i2svg();
dom.watch();

Call it before dom.i2svg() and dom.watch(), and import it from its own file, not from ig::common-js. In nest mode the fa-* classes and svg-inline--fa move to the <svg> while other classes stay on the <i>, so styles that select svg directly under an element, or i.fa-…, need adjusting.

Missing Icons

Font Awesome draws an icon that was never added to its library as a pulsing placeholder and logs nothing. ig::common-js watches the page for such placeholders and logs each one once as a console error that names what to register, e.g. add faEllipsisVertical from @fortawesome/free-solid-svg-icons to library.add(). Browser tests that end with assertNoJavascriptErrors() therefore fail on a page that shows a missing icon, including one inside a package component. An icon shown only in a state no test reaches, such as the drag handle of an overflowing carousel, still needs a look in the browser.

Traits

Ulid32 Trait

Provides ULID (Crockford Base32) utility methods for Eloquent models. Generates 26-character Base32-encoded UUIDs and adds human-readable formatting, URL generation, and link rendering.

use InternetGuru\LaravelCommon\Traits\Ulid32;

class Order extends Model
{
    use Ulid32;
}

Available methods:

Method Description
$model->ulidForHumans() Formats the ULID with dashes (e.g. 01JM-ABCDEF-GHIJKL-MNOPQR-STUV).
$model->shortUlidForHumans() Returns the last 7 characters of the formatted ULID.
$model->ulidUrl($usp) Generates a URL to the model's show route.
$model->ulidLink($content) Renders an HTML link to the model.
Model::generateBase32Uuid() Generates a new Crockford Base32-encoded UUID (26 characters).

Rules

Ulid32 Validation Rule

Validates that a value is a valid 26-character Crockford Base32 ULID (no I, L, O, U characters).

Can be used as a class-based rule or via the globally registered ulid32 rule:

// Class-based
use InternetGuru\LaravelCommon\Rules\Ulid32;

$request->validate([
    'code' => ['required', new Ulid32],
]);

// String-based (registered globally by CommonServiceProvider)
$request->validate([
    'code' => 'required|ulid32',
]);

Services

GeolocationService

Resolves an IP address to a geographic location using the torann/geoip package. Results are cached and rate-limited (5 lookups per 60 seconds).

use InternetGuru\LaravelCommon\Services\GeolocationService;

$geoService = app(GeolocationService::class);
$location = $geoService->getLocation('8.8.8.8');

echo $location->timezone; // "America/Chicago"
echo $location->country;  // "US"

Throws GeolocationServiceException on failure or rate limit.

Notifications

BaseNotification

Abstract queued notification class that captures the requester (IP, user ID, URL) at creation time and sends via the mail channel.

Features:

  • Queued with 10 retries and 2-minute backoff.
  • Retry middleware via LogNotificationFailure — logs warnings on transient failures.
  • Captures the requester's IP, authenticated user ID and current page URL; the footer names the IP and its time zone, looked up by geolocation when the mail is built.
  • Raised in a queue job or by the scheduler, it has no requester, and the footer leaves the line out.
  • Raised on someone else's behalf, e.g. staff accepting a customer's payment, call ->withoutRequester() so the recipient does not see the staff member's address: $order->notify((new PaymentReceived)->withoutRequester()).
  • Logs permanently failed notifications.

Extend this class to create your own notifications:

use InternetGuru\LaravelCommon\Notifications\BaseNotification;

class OrderConfirmation extends BaseNotification
{
    public function toMail(object $notifiable): MailMessage
    {
        return (new \InternetGuru\LaravelCommon\Mail\MailMessage)
            ->setExtraMailData($this->getExtraMailData())
            ->subject('Order Confirmed')
            ->view(['html' => 'emails.order-confirmed', 'text' => 'emails.order-confirmed-text']);
    }
}

MailMessage

Extends Laravel's MailMessage with automatic reference number generation, no-reply detection, and extra mail data injection.

Features:

  • Appends a random reference code (Ref XXXXX) to every subject line for tracking.
  • Automatically detects no-reply addresses and adds a "replies not delivered" note.
  • Supports arbitrary extra data (setExtraMailData) passed to email views (IP, timezone, user ID, etc.).

Available methods:

Method Description
->to($address, $name) Set one or multiple recipients. Accepts a single address or an array of [email => name] pairs.
->withoutRefNumber() Suppress the Ref XXXXX suffix from the subject and footer.
->setRefNumber($ref) Override the auto-generated reference code.
->setExtraMailData($data) Merge additional data passed to the email view.

Mail Logging

All sent mail notifications are automatically logged to the mail_logs database table via the LogSentNotification listener.

Publish the migration to create the mail_logs table:

php artisan vendor:publish --tag=ig-common:migrations
php artisan migrate

Logged fields: to, replyto, subject, notification (the notification class), created_at, updated_at. The body is not kept, because it can carry sign-in PINs and links; the body column stays only for older rows and is emptied by the 2026-11-14 migration.

Exception Handling

The package registers a custom exception handler that provides user-friendly error pages and JSON responses for common HTTP errors (401, 402, 403, 404, 419, 429, 500, 503).

Features:

  • Read-only mode: DbReadOnlyException returns a 503 response (JSON or redirect with error).
  • Connection errors: ConnectException returns a friendly error message.
  • Rate limiting (429) and session expiration (419): Handled with translated messages.
  • Debug mode: Uses dd() for detailed exception inspection.
  • JSON support: Returns JSON responses when the request expects JSON.
  • Redirects to the previously tracked page (via SetPrevPage middleware) on error.
  • Unknown addresses: A Route::fallback in the web group answers 404, so the error page has the session. An application's own fallback route takes precedence.
  • 503 auto-refresh: The 503 error page automatically reloads after 30 seconds.
  • Testing: Exceptions are left to Laravel, except HTTP errors on HTML pages, which render the styled error page as in production.

Custom error views are included for standard HTTP status codes. The error pages use the ig-common::layouts.base layout.

Logging

The package defines the deprecations log channel at boot from logging.deprecations.channel (LOG_DEPRECATIONS_CHANNEL, null by default), unless logging.channels.deprecations is already set. Laravel would otherwise add it only on the first deprecation, which under Octane misses the request's config copy and ends in the emergency logger.

Under phpunit and Pest, the default log channel is null, so test runs stay out of storage/logs, which they share with the running application. LOG_CHANNEL does not change this, because an application's .env usually sets it to stack. Tests that check logging use Log::spy() or Log::shouldReceive(), which are not affected.

JsonDailyLogger

A custom Monolog logger that writes JSON-formatted daily rotating log files enriched with request context.

Each log entry includes, under extra.context:

  • User: user.id (if authenticated).
  • Session: session, the first 12 hex digits of the session ID's SHA-256, so lines of one visit can be grouped (null without a started session).
  • App info: Git branch and commit.
  • Request info: request_info with url (the path), ip, http_method and server.

It deliberately leaves out names, e-mail addresses, request input, the raw session ID, the referrer and the user agent, so the log holds no personal data or secrets on its own. Pass what a line is about in its context, as ids: Log::info('Settings updated', ['setting_ids' => $ids]).

Configuration in config/logging.php:

'channels' => [
    'json_daily' => [
        'driver' => 'custom',
        'via' => InternetGuru\LaravelCommon\Logging\JsonDailyLogger::class,
        'path' => storage_path('logs/app.log'),
        'days' => 14,
        'level' => 'debug',
    ],
],

Localization

The package includes translations in English (en), Czech (cs), and Danish (da) for:

  • Error pages (errors.php) – HTTP status messages and descriptions.
  • Layout strings (layouts.php) – Footer, email templates, support links, and UI labels.
  • System messages (messages.php) – Validation messages, email labels, and demo mode warnings.
  • Navigation (navig.php) – Breadcrumb labels for routes.

Publishing Assets

You can publish package assets to customize them:

# Publish database migrations
php artisan vendor:publish --tag=ig-common:migrations

# Publish configuration
php artisan vendor:publish --tag=ig-common:config

# Publish views for customization
php artisan vendor:publish --tag=ig-common:views

# Publish language files
php artisan vendor:publish --tag=ig-common:lang

Considerations

Changes worth considering that were not carried out yet: what to do and why.

  • Mail log: store the bare address. LogSentNotification stores the whole header in mail_logs.to and replyto, e.g. To: jane@example.com. Store only the addresses, from getAddresses(), and decide whether to strip the prefix from the rows already stored.
  • Applications: update to 9.6.2 or later. Apps on an older version still log names, e-mail addresses and form input on every line, and keep e-mail texts with sign-in PINs. giftcarder, steakgrill and martapavelka are updated; the other apps deployed by docker-ansible (moss, petrolbusiness, cut-tech, ak-beranek, vokom and the rest in its group_vars) are not. Each needs vendor:publish --tag=ig-common:migrations and the migration in the same commit, since mail fails without the notification column.
  • Security: prune the mail log. mail_logs keeps the recipient, reply-to and subject of every e-mail forever. Make MailLog prunable (for example after 90 days, configurable) and schedule model:prune, so the table does not grow into a list of every address the application ever wrote to.
  • Security: redact secrets inside messages. The log processor no longer adds request input, but a message or an exception message can still carry a secret: Guzzle puts the full request URL, query string included, into its exception messages (an API key sent as ?key=), and a QueryException includes the SQL bindings. Add a processor step that masks the values of query parameters such as key, token, secret, code and pin, in the message and in a logged exception's message.
  • Generalize the share button. share-page always opens the same modal: a QR code and the page URL to copy. Turn it into a share menu that projects and individual pages add their own items to, through a slot, a stack or a registry, so laravel-model-browser can offer its exports (CSV download, copying the current page) there instead of in buttons of its own. Allow placing it anywhere, as a full button or as an icon only, for example next to the hamburger menu icon, and keep the footer link as it is when nothing is added.

License & Commercial Terms

License

Copyright © 2026 Internet Guru

This software is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) license.

Disclaimer: This software is provided "as is", without warranty of any kind, express or implied. In no event shall the authors or copyright holders be liable for any claim, damages or other liability.

Commercial Use

The standard CC BY-NC-SA license prohibits commercial use. If you wish to use this software in a commercial environment or product, we offer flexible commercial licenses tailored to:

  • Your company size.
  • The nature of your project.
  • Your specific integration needs.

Note: In many instances (especially for startups or small-scale tools), this may result in no fees being charged at all. Please contact us to obtain written permission or a commercial agreement.

Contact for Licensing: info@internetguru.io

Professional Services

Are you looking to get the most out of this project? We are available for:

  • Custom Development: Tailoring the software to your specific requirements.
  • Integration & Support: Helping your team implement and maintain the solution.
  • Training & Workshops: Seminars and hands-on workshops for your developers.

Reach out to us at info@internetguru.io — we are more than happy to assist you!