Laravel 10 - How to Use New @style Attribute

Laravel 10 - How to Use New @style Attribute

Laravel 10: How to Use the New @style Blade Attribute

Laravel 10 introduced a new Blade directive called @style, which allows you to conditionally apply inline styles more cleanly and expressively—without cluttering your Blade files with multiple @if/@else blocks.

Let’s walk through how it works and how it simplifies style management directly in your Blade templates.

Note: This feature is available from Laravel 10.0 onwards.

Table of Contents

  1. Why Use @style?

  2. Example 1 – Traditional @if Style Handling

  3. Example 2 – Using @style for Cleaner Conditional Styles

1. Why Use @style?

Before Laravel 10, if you wanted to conditionally apply inline styles, you'd typically use Blade conditionals (@if, @else) and duplicate HTML elements. This can quickly become verbose and hard to maintain.

Laravel 10 introduces the @style directive, allowing you to inline styles more cleanly, even with conditional logic.

2. Example 1 – Traditional @if Style Handling

Here’s how we used to conditionally apply styles before:

@php $isActive = false; @endphp @if($isActive) <span style="background-color: red; color: white;"> When $isActive is true </span> @else <span style="background-color: red; color: green;"> When $isActive is false </span> @endif <span style="background-color: red; font-weight: bold;">hello</span>

While this works, it duplicates the <span> tag and bloats your Blade file.

3. Example 2 – Using @style For Cleaner Conditional Styles

Now with Laravel 10, you can write the same logic much more cleanly using @style:

@php $isActive = false; @endphp <span @style([ 'background-color: red', 'color: white' => $isActive, 'color: green' => !$isActive, ])> This is using the @style directive </span>

Output:

<span style="background-color: red; color: green;"> This is using the @style directive </span>

As you can see, Laravel will intelligently evaluate the conditions and apply the correct styles inline.

Final Thoughts

The @style Directive is a powerful enhancement to Blade templates that allows for clean, readable, and dynamic inline styles. It’s especially helpful in situations where the logic is simple but the style needs to be conditionally applied.

Thanks for being so supportive! Keep exploring Laravel's awesome features.

Souy Soeng

Souy Soeng

Hi there šŸ‘‹, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
šŸ‘Æ I’m looking to collaborate on open-source PHP & JavaScript projects
šŸ’¬ Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close