MasterPHP.in
Try Compiler →
Laravel Tutorial

Laravel Tailwind CSS and Alpine.js with Vite


Your invoice app works, but it still looks like a page from 2005. The layout, the badge and the cards are all unstyled, and the owner wants something that looks professional before the first client sees it. There is also a small request on the list: the detail page should have a button that shows or hides the GST breakdown, and the new-invoice form should show a live line total as the user types the quantity and rate.

You could write a CSS file with hundreds of custom class names, and some JavaScript with document.querySelector calls to toggle things. That works, but both pieces grow messy quickly. Class names clash, the JavaScript gets tied to the exact HTML, and nobody remembers what .box2 was for.

Laravel’s default answer is three tools that work together. Tailwind CSS styles your pages with small utility classes, Alpine.js adds light interactions directly in your HTML, and Vite builds and serves both. In this lesson you will connect them to your Blade pages and use them on the invoice app.

The Problem: Hand-Written CSS and Scattered JavaScript

Here is the usual way a beginner would hide and show the GST breakdown:

<button id="gst-toggle">Show GST breakdown</button>
<div id="gst-box" style="display: none;">...</div>

<script>
    document.getElementById('gst-toggle').addEventListener('click', function () {
        var box = document.getElementById('gst-box');
        box.style.display = box.style.display === 'none' ? 'block' : 'none';
    });
</script>

This has real problems:

  • The behaviour lives far from the button it controls, so you must hunt through the file to understand it.
  • It depends on id values. Use the component twice on one page and the ids clash.
  • The button text never changes, and adding that means more code.

You will see the same job done with Alpine.js later in this lesson, in a few lines placed right on the element.

 

What Each Tool Does

The three tools have separate jobs:

  • Tailwind CSS is a CSS framework made of small single-purpose classes. You build a design by combining them in your HTML, instead of writing new CSS.
  • Alpine.js is a tiny JavaScript library. You add attributes like x-data and x-show to your HTML, and it handles clicks, toggles and live values.
  • Vite is the build tool. It takes your CSS and JavaScript source files, processes them, and serves them to the browser.

This is how they connect:

resources/css/app.css  (Tailwind lives here)  --\
                                                 >-- Vite --> browser
resources/js/app.js    (Alpine lives here)    --/
                                                 ^
                     @vite([...]) in your Blade layout asks Vite for these files

The key idea is that you do not link to the CSS and JS files directly. You write @vite in your layout, and Laravel works out the correct address, whether you are developing locally or running the built version in production.

 

Checking Your Frontend Setup

Node.js and npm

Vite and Tailwind run on Node.js, which you install separately from PHP. Check that it is available:

node -v
npm -v

If either command fails, install a current LTS version of Node.js from nodejs.org, then open a new terminal. Node is only needed on your development machine to build the CSS and JavaScript. Visitors never run it.

 

What a Fresh Project Already Contains

A new Laravel 13 project is already prepared for this. Open vite.config.js in the project root. It looks close to this:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
        tailwindcss(),
    ],
});

Three things matter here:

  • input lists the two entry files that Vite builds.
  • refresh: true reloads your browser automatically when you save a Blade file.
  • tailwindcss() is the official Tailwind plugin. It is why you do not need any other Tailwind setup.

Now open resources/css/app.css. The first line is the one that turns Tailwind on:

@import 'tailwindcss';

@source '../**/*.blade.php';
@source '../**/*.js';

The @source lines tell Tailwind which files to scan for class names. It then generates CSS only for the classes you actually used, so the final file stays small. Your file may contain a few more lines, such as a font setting, which you can leave alone.

There is no tailwind.config.js in a modern project. Tailwind version 4 keeps its configuration inside the CSS file. Many older tutorials still show tailwind.config.js and @tailwind base; lines, which belong to version 3. If you see those, you are reading an outdated guide.

 

Installing the Packages

The JavaScript packages are listed in package.json, but they are downloaded into a node_modules folder, just like vendor for Composer. If the folder is missing, install them:

npm install

Like vendor, the node_modules folder is excluded from Git, and you should never edit anything inside it.

 

How Vite Connects to Blade

Add the @vite directive to the <head> of your layout:

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@yield('title', 'Invoice Manager') | {{ config('app.name') }}</title>

    @vite(['resources/css/app.css', 'resources/js/app.js'])
    @stack('styles')
</head>

This one line prints the correct <link> and <script> tags. How it behaves depends on which command you run:

npm run dev

This starts the Vite development server and leaves it running. Laravel creates a public/hot file, and @vite then points the browser at the dev server. Your CSS and JavaScript changes appear instantly, without a full reload. Keep this terminal open while you work, next to php artisan serve.

npm run build

This creates the production version. Vite writes compressed files with a hash in their names into public/build, along with a manifest.json file. @vite reads that manifest and prints the right file names. You will run this command during deployment later in the course.

When the dev server is running, @vite uses it. When it is not, @vite falls back to the built files. If neither exists, you get an error, which is described in the Common Mistakes section.

 

Tailwind CSS Basics

Utility Classes

With Tailwind, you style an element by adding small classes that each do one job:

<div class="bg-white p-6 rounded-lg shadow">
    <h2 class="text-xl font-bold">Invoice 1001</h2>
    <p class="mt-2 text-gray-600">Client: Sharma Traders</p>
</div>

Each class maps to simple CSS:

  • bg-white is a white background.
  • p-6 is padding. The number is a scale, where each step is 0.25rem, so p-6 means 1.5rem.
  • rounded-lg rounds the corners, and shadow adds a soft shadow.
  • text-xl font-bold sets a bigger, bold font.
  • mt-2 is a small top margin, and text-gray-600 is a grey text colour.

It feels strange at first, since the class list gets long. The benefit is that you never invent names, never switch between files, and deleting an element also deletes its styling. The long class lists will be tamed by Blade components, as you will see in the next lesson.

 

Responsive and Hover Variants

Tailwind is mobile first. A class with no prefix applies to every screen size, and a prefix like md: applies from that screen width upward:

<div class="flex flex-col gap-4 md:flex-row">
    <a href="#" class="rounded bg-indigo-600 px-4 py-2 text-white hover:bg-indigo-700">
        Create invoice
    </a>
</div>

On a phone, the items stack in a column. From the medium breakpoint upward, they sit in a row. The hover: prefix applies a class only while the mouse is over the element. Many Indian users open your app on a phone, so always check the narrow view first.

 

Styling the Layout

Here is the body of the layout from the Layouts lesson, now with Tailwind classes:

<body class="bg-gray-50 text-gray-800">
    <header class="border-b bg-white">
        <div class="mx-auto flex max-w-5xl items-center justify-between px-4 py-4">
            <h1 class="text-xl font-bold">{{ config('app.name') }}</h1>

            <nav class="flex gap-4 text-sm">
                <a href="{{ route('invoices.index') }}"
                   class="{{ request()->routeIs('invoices.*') ? 'font-semibold text-indigo-600' : 'text-gray-600 hover:text-indigo-600' }}">
                    Invoices
                </a>
            </nav>
        </div>
    </header>

    <main class="mx-auto max-w-5xl px-4 py-8">
        @session('status')
            <p class="mb-4 rounded bg-green-100 px-4 py-2 text-green-800">{{ $value }}</p>
        @endsession

        @yield('content')
    </main>

    <footer class="py-6 text-center text-sm text-gray-500">
        &copy; {{ date('Y') }} MasterPHP Traders
    </footer>

    @stack('scripts')
</body>

The active menu link uses the same routeIs() idea you wrote earlier, but now it returns Tailwind classes. The flash message block and the stacks keep working as before. In the next lesson, you will turn the navbar and the alert into reusable components.

 

Dynamic Classes: Use Full Class Names

Here is the status badge from the Anonymous Components lesson, now with real colours:

@props(['status' => 'pending'])

@php
    $styles = match ($status) {
        'paid'    => 'bg-green-100 text-green-800',
        'overdue' => 'bg-red-100 text-red-800',
        default   => 'bg-yellow-100 text-yellow-800',
    };

    $label = match ($status) {
        'paid'    => 'Paid',
        'overdue' => 'Overdue',
        default   => 'Pending',
    };
@endphp

<span {{ $attributes->class(['inline-flex rounded-full px-2.5 py-0.5 text-xs font-medium', $styles]) }}>
    {{ $label }}
</span>

Notice that every class name is written out in full. Tailwind finds classes by scanning your files for text that looks like a class. It cannot run your PHP. If you wrote 'bg-' . $color . '-100', Tailwind would never see the word bg-green-100, and that style would be missing from the final CSS. Always write complete class names, even if it means repeating a little.

 

Customizing with @theme

When you need your own brand colour, add it in app.css. Tailwind 4 reads design settings from a @theme block:

@theme {
    --color-brand-600: #4f46e5;
}

You can now write bg-brand-600 or text-brand-600 in any Blade file. Change the value once, and every element using it follows. This replaces the old tailwind.config.js file.

 

Alpine.js Basics

Installing Alpine

A fresh project does not include Alpine, so add it with npm:

npm install alpinejs

Then start it in resources/js/app.js. Keep any import lines that are already there, and add these:

import Alpine from 'alpinejs';

window.Alpine = Alpine;

Alpine.start();

Vite bundles Alpine into your app.js file, and your layout already loads it through @vite. You can also load Alpine from a CDN with a script tag, which is fine for quick tests, but this course uses npm so that everything is built in one place.

 

Your First Alpine Component: Show and Hide

Here is the GST breakdown from the start of the lesson, written with Alpine:

<div x-data="{ open: false }">
    <button type="button" @click="open = ! open" class="text-sm text-indigo-600">
        <span x-text="open ? 'Hide GST breakdown' : 'Show GST breakdown'"></span>
    </button>

    <div x-show="open" x-cloak class="mt-3 rounded border bg-white p-4 text-sm">
        <p>Amount: ₹ {{ number_format($invoice['total']) }}</p>
        <p>GST (18%): ₹ {{ number_format($invoice['total'] * 0.18) }}</p>
        <p>Total: ₹ {{ number_format($invoice['total'] * 1.18) }}</p>
    </div>
</div>

There are four Alpine attributes at work:

  • x-data="{ open: false }" creates a small piece of state. Everything inside this element can read and change open.
  • @click="open = ! open" runs when the button is clicked and flips the value.
  • x-show="open" shows the box only while open is true.
  • x-text sets the text of the element from an expression, so the button label changes by itself.

The behaviour is right on the elements it controls, no ids are needed, and you can place this block twice on a page without a clash. The PHP values inside, like number_format(...), are still printed by Blade on the server, before Alpine runs in the browser.

 

Live Values with x-model

The x-model attribute connects an input to a value, so anything that uses the value updates as the user types. This is perfect for the line total on the new invoice form:

<div x-data="{ qty: 1, rate: 500 }" class="grid gap-3 md:grid-cols-3">
    <input type="number" x-model.number="qty" min="1" class="rounded border px-3 py-2">
    <input type="number" x-model.number="rate" min="0" class="rounded border px-3 py-2">

    <p class="py-2 font-semibold">
        Line total: ₹ <span x-text="(qty * rate).toLocaleString('en-IN')"></span>
    </p>
</div>

The .number modifier turns the typed text into a real number, so qty * rate is a multiplication and not a string join. toLocaleString('en-IN') formats the result with Indian digit grouping, so 125000 appears as 1,25,000. This is only a display helper for the user. The real total must still be calculated and checked on the server, which you will do in the Forms & Validation chapter.

 

Passing PHP Data into Alpine

Sometimes Alpine needs a value that PHP knows. Use the @js directive, which prints PHP data as safe JavaScript:

<div x-data="{ status: @js($invoice['status']) }">
    <p x-show="status === 'overdue'" class="text-red-600">
        This invoice is overdue. Send a reminder.
    </p>
</div>

Do not build this by hand with quotes and {{ }}. A name like Sharma's Traders would break the JavaScript, while @js escapes it correctly.

 

Alpine Inside Blade Components

Your anonymous components already pass extra attributes through the attribute bag, so Alpine attributes work on them without any changes:

<x-button type="button" x-on:click="open = true">Add line item</x-button>

There is one catch. Blade treats an attribute starting with a single colon on a component tag as a PHP expression. Alpine’s shorthand :class looks the same, so Blade tries to run it as PHP. To send an Alpine binding to a component, use the long form or a double colon:

<x-button x-bind:class="open ? 'opacity-50' : ''">Save</x-button>

<x-button ::class="open ? 'opacity-50' : ''">Save</x-button>

On normal HTML elements, like <div> or <button>, the single colon form is fine. The issue is only on <x-...> tags.

 

Preventing the Flash of Hidden Content

In the GST example, the box has x-cloak. Without it, content hidden by x-show can flash on screen for a moment before Alpine starts. Add this rule to resources/css/app.css once:

[x-cloak] {
    display: none !important;
}

Alpine removes the x-cloak attribute when it is ready, and the element then follows x-show.

 

Common Mistakes

Mistake 1: Vite Manifest Not Found

You open a page and see:

Illuminate\Foundation\ViteManifestNotFoundException:
Vite manifest not found at: /var/www/invoice-app/public/build/manifest.json

This means @vite found neither the dev server nor the built files. Run npm run dev for development, or npm run build to create the production files.

 

Mistake 2: Vite Command Not Found

Running npm run dev fails on Windows with:

'vite' is not recognized as an internal or external command

On Linux or macOS the message is sh: vite: command not found. The packages were never installed. Run npm install first, then try again.

 

Mistake 3: Page Loads but Has No Styling

There is no error, the page simply looks plain. Check these in order:

  • The @vite line is missing from the layout’s <head>.
  • Neither npm run dev is running nor a build exists, so there is no CSS to load.
  • @import 'tailwindcss'; is missing from resources/css/app.css.

 

Mistake 4: Building Class Names with PHP

<span class="bg-{{ $color }}-100">

This will look fine for some colours and wrong for others. Tailwind never saw the full class name, so it did not generate the CSS. Use complete names, as in the badge example, or a match that returns whole strings.

 

Mistake 5: Alpine Is Not Working

You add x-data and click the button, and nothing happens. Open the browser console. If you see:

Alpine Expression Error: open is not defined

then the element using open is outside the x-data element. State is only visible inside the element that defines it. If there is no Alpine error at all, check that Alpine.start() is called in app.js and that npm run dev or a fresh build is running.

 

Mistake 6: Using :class on a Component Tag

<x-button :class="open ? 'opacity-50' : ''">Save</x-button>

Blade sends this to PHP, which does not know the word open:

Error: Undefined constant "open"

Use x-bind:class or ::class on component tags, as shown earlier.

 

Quick Summary

  • Tailwind CSS styles with utility classes, Alpine.js adds interactions in HTML attributes, and Vite builds both.
  • A fresh Laravel 13 project already has Vite, the Tailwind plugin and a resources/css/app.css with @import 'tailwindcss';.
  • Run npm install once, npm run dev while working, and npm run build for production files.
  • Load your assets with @vite(['resources/css/app.css', 'resources/js/app.js']) in the layout’s <head>.
  • Tailwind 4 has no tailwind.config.js. Customize colours and fonts in @theme inside the CSS file.
  • Tailwind is mobile first. Prefixes like md: and hover: add responsive and state styles.
  • Always write complete class names, because Tailwind cannot read classes built by PHP.
  • Install Alpine with npm install alpinejs, then start it in resources/js/app.js.
  • Use x-data, @click, x-show, x-text and x-model for toggles and live values.
  • Use @js() to pass PHP data to Alpine, and x-cloak with a CSS rule to avoid flicker.
  • On component tags, write x-bind:class or ::class instead of :class.
  • Client-side calculations are only for display. Always validate and calculate again on the server.

 

What’s Next

You now have a styled layout, a coloured status badge and your first Alpine interactions, but the pieces are still scattered across pages. In the next lesson, Building a Reusable UI Kit, you will turn them into a small set of Blade components, starting with a navbar, an alert and a card, so that every new page looks consistent from the first line.

Frequently Asked Questions

Usually no. A new Laravel project comes with Tailwind configured through the Vite plugin, so you only need to run npm install to download the packages. If you are adding Tailwind to an older project, you install the tailwindcss and @tailwindcss/vite packages and add the plugin to vite.config.js.
The dev command starts a live development server that updates your browser instantly when you change CSS, JavaScript or Blade files. The build command creates optimized, versioned files in public/build for a live site. You use dev while coding and build when you deploy.
There is no such file in a fresh project because Tailwind version 4 keeps its settings in the CSS file. You add custom colours, fonts and other design values inside a theme block in resources/css/app.css. Older tutorials that mention tailwind.config.js were written for Tailwind version 3.
No. Alpine is designed for small interactions inside server-rendered pages, such as dropdowns, toggles, modals and live totals. Vue and React are better for large single-page applications with complex state and routing. For most Blade-based Laravel apps, Alpine is enough.

Share this tutorial