$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[September 25, 2025] Laravel

Laravel + Alpine.js: Lightweight JS

Laravel + Alpine.js: Lightweight JS

────────────────────────────────────────────────────────

Laravel + Alpine.js: Lightweight JS

Tip: Include Alpine

<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

Gotcha: x-data Directive

<div x-data="{ open: false }">
    <button @click="open = !open">Toggle</button>
    <div x-show="open">Content</div>
</div>

Tip: x-model for Two-Way Binding

<input x-model="message">
<p x-text="message"></p>

Gotcha: x-init for Initialization

<div x-init="console.log('loaded')"></div>

Tip: x-for for Loops

<template x-for="item in items" :key="item.id">
    <span x-text="item.name"></span>
</template>

Gotcha: Alpine + Livewire

Alpine and Livewire work together seamlessly. Use Alpine for client-side, Livewire for server-side.

Tip: Use route:cache Carefully

php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.

Tip: Model APP_KEY Rotation

Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.

Gotcha: Local Scope Leaks

Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.

Senior Insight

The Laravel + Alpine.js stack is my default choice for new projects that need interactivity without a full frontend framework. The key insight I share with teams: treat Alpine as a progressive enhancement, not an application framework. Server-render the initial state, use Alpine only for interactions that genuinely need client-side reactivity (dropdowns, modals, live search), and never store application state in Alpine x-data that should live in the database.

Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)

────────────────────────────────────────────────────────
<-- back to posts