Laravel — P67: HTML Attribute Directives in Blade
--
In the last article we covered the @class
and @style
directives to implement conditional styling in Blade. But, there are other HTML attribute directives that are present in Blade that we can utilize:
@checked
directive@selected
directive@disabled
directive@readonly
directive@required
directive
@checked directive
With the @checked
directive, the radio button or checkbox will be checked if the condition is truthy.
Route::get('/directive-test', function () {
return view('html-directives.index', ['isActiveVar' => true]);
});
The $isActiveVar
variable is set to true
and passed to the html-directives.index
Blade file.
<label for="isActive">Is Active?</label>
<input type="checkbox"
id="isActive"
name="isActive"
value="isActive"
@checked( old('isActive', $isActiveVar) ) />
Inside the Blade file, the @checked
directive accepts an argument that will be truthy. In this scenario, we pass the old()
function that will preserve the state once the form is refreshed. The name of the checkbox
is isActive
, which is why we pass isActive
into old()
. If it’s a brand new connection to the form, we simply use the value of $isActiveVar
. This is the code that it generates.
<label for="isActive">Is Active?</label>
<input type=”checkbox” id=”isActive” name=”isActive” value=”isActive” checked=””>
To see it without the old()
, we simply pass the variable directly from the route.
<label for="isActiveTwo">Is Active Two?</label>
<input type="checkbox"
id="isActiveTwo"
name="isActiveTwo"
value="isActiveTwo"
@checked( $isActiveVar ) />
@selected directive
Now that we have the fundamental understanding of how the @checked
directive functions, the other ones should be a piece of cake.
<label for="car">Car Select</label>…