Laravel Breeze comes with a lot of pre-built components that use Tailwind. They are located in the resources/views/components
directory.
Let's look into the text input component:
resources/views/components/text-input.blade.php
@props(['disabled' => false]) <input {{ $disabled ? 'disabled' : '' }} {!! $attributes->merge(['class' => 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm']) !!}>
Tailwind classes are defined inside the component. Developers can easily reuse components without repeating CSS or writing custom classes.
<x-text-input type="text" />
Another benefit of this structure is quickly changing the component's appearance by adding or removing Tailwind classes without searching for the correct class in many CSS files.
Sometimes, you need slight modifications to your components. For instance, text should be uppercase for that text-input
component.
All Blade components in Laravel have a particular variable named $attributes
, the attributes bag. It has the ->merge()
method to define default classes.
The syntax is as follows:
{!! $attributes->merge(['class' => '...']) !!}
Now, we can add just a single Tailwind class to our component, and it will be merged with all default classes inside the component, rendering us an input field where all input is in uppercase.
<x-text-input type="text" class="uppercase" />
You can define your custom properties on the component and use them as data variables using the @props
Blade directive.
Let's modify the default text-input
component and add more props:
resources/views/components/text-input.blade.php
@props([ 'disabled' => false, 'description' => '', 'default' => '']) <div> <input {{ $disabled ? 'disabled' : '' }} {!! $attributes->merge(['class' => 'border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm']) !!} value="{{ $default }}" > <div class="text-gray-600">{{ $description }}</div></div>
Now, in our view, we can define components like this:
@php $customVariable = 'Laravel Daily';@endphp <x-text-input type="text" :default="$customVariable" description="Your name in latin characters"/>
It gives the following result:
Notice that when we have a colon :
prefix before the attribute, the value between double quotes ""
is evaluated by PHP. That can be useful for more complex logic.
The @class
directive conditionally compiles a CSS class string. It accepts an array of classes where the array key contains the classes you wish to add, while the value is a boolean expression.
@php $isActive = true;@endphp <div @class([ 'p-4', 'font-bold' => $isActive, 'text-gray-500' => ! $isActive,])>This is active text</div> @php $isActive = false;@endphp <div @class([ 'p-4', 'font-bold' => $isActive, 'text-gray-500' => ! $isActive,])>This is inactive text</div>
More information on Blade capabilities could be found in the Official Laravel Documentation