Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Set default value for attributes in components using @props directive in Laravel

As I described in this article on how you can create anonymous components in Laravel, we can create an <x-alert> component with the following content.

<!-- /resources/views/components/alert.blade.php -->

<div class="alert">
    {{ $slot }}
</div>

Which can be rendered in another Blade view using the component’s tag like so.

<x-alert>
    Default slot content...
</x-alert>

Now, we can pass additional attributes to the component which will be available to the component template. For instance, if we pass in a type attribute to the component like so.

<x-alert type="success">
    Default slot content...
</x-alert>

This type attribute can be utilized in the component template like so.

<div class="{{ $type == 'success' ? 'class-green' : 'class-red' }}">
    {{ $slot }}
</div>

But sometimes, you just want to keep a default value for the attribute irrespective of passing it down from the component. So, if we don’t provide any type attribute like so, in the previous example…

<x-alert>
    Default slot content...
</x-alert>

It should still work. Luckily, Laravel has a solution for this as well. Enter @props directive.

The @props directive

The @props directive can be used to specify a default value for the attributes at the top of the component’s Blade template. So, if we want to set the type attribute’s default value to success, we can do it like so.

@props([
    'type' => 'success'
])

<div class="{{ $type == 'success' ? 'class-green' : 'class-red' }}">
    {{ $slot }}
</div>

Now, when we don’t pass the type attribute to the <x-alert> component, it will use the default value of it which we’ve set in the @props directive and overrides its default value when we pass it down from the component. For instance, type="error" in our case like so.

<x-alert type="error">
    Default slot content...
</x-alert>

The value of $type will be error in this case.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?