Laravel 10 - How to Use New @style Attribute
Hello Artisan, today I'll show you how to use @style in our Laravel app. Using this directive we can easily add any style to that tag. So, let's see how we can use this @style attribute.
Note: Tested on Laravel 10.0
If we back in the previous moments, where if we need any change is style, we need to use so called @if @endif directive. Like below
@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>
Which is so tidy to use. Let's proceed to the next step.
We can achieve the same result what we do in #step1 using @style attribute with more shorthand and concise way. Let's look at the below code snippet.
@php
$isActive = false;
@endphp
<span @style([
'background-color: red',
'color: white' => $isActive,
'color: green' => !$isActive,
])>When $isActive is true</span>
<span style="background-color: red; font-weight: bold;">hello</span>
Which'll produce the below result.
So, we can see that @style can give us the same result with less and readable code.
That's it for today. I hope this will help in future works. Thanks for reading. ๐