How to Add Alpine.js to a Laravel Project
Alpine.js is a lightweight JavaScript framework that makes it easy to add interactivity to your Laravel applications. Here’s how you can integrate Alpine.js into any Laravel project.
Step 1: Install Alpine.js
There are two main ways to add Alpine.js to your Laravel project:
Option 1: Include via CDN (Recommended for Simplicity)
Add the following script inside your main Blade file (resources/views/layouts/app.blade.php
or any other Blade file):
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
This will load Alpine.js from a CDN and enable its features immediately.
Option 2: Install via NPM (Recommended for Advanced Use Cases)
If you're using Laravel with a frontend build system like Vite, you can install Alpine.js via NPM:
npm install alpinejs
Then, import it into your app.js or bootstrap.js file (resources/js/app.js
or resources/js/bootstrap.js
):
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
Next, make sure to run:
npm run dev
This will bundle Alpine.js with your Laravel assets.
Step 2: Use Alpine.js in Blade Templates
Now, you can start using Alpine.js in your Blade templates.
Example 1: Toggle Visibility
<div x-data="{ open: false }">
<button @click="open = !open">Toggle</button>
<div x-show="open" class="p-4 bg-gray-200 mt-2">Hello, Alpine.js!</div>
</div>
Example 2: Simple Counter
<div x-data="{ count: 0 }">
<button @click="count++" class="px-4 py-2 bg-blue-500 text-white">Increase</button>
<span class="ml-4 text-xl">Count: <strong x-text="count"></strong></span>
</div>
Step 3: Using Alpine.js with Laravel Components
If you're using Laravel Blade components, Alpine.js can enhance interactivity easily.
Example: Dynamic Dropdown in a Blade Component
<div x-data="{ open: false }">
<button @click="open = !open" class="bg-blue-500 text-white px-4 py-2">Dropdown</button>
<ul x-show="open" class="border mt-2">
<li class="p-2">Item 1</li>
<li class="p-2">Item 2</li>
<li class="p-2">Item 3</li>
</ul>
</div>
Conclusion
Now you have Alpine.js integrated into your Laravel project, allowing you to add simple interactivity without writing complex JavaScript. Whether you choose the CDN method for quick usage or NPM for better asset management, Alpine.js is a great addition to Laravel projects.
Would you like help with a specific feature using Alpine.js in Laravel?