MasterPHP.in
Try Compiler →
Laravel Tutorial

Laravel Anonymous Components and Attribute Bags


In the last two lessons you built a status badge as a class-based component and learned when a partial is enough. Now look at that badge again. It has a PHP class with one constructor argument, one small method and a render() method, all to print a single <span>. That is a lot of ceremony for something so small.

There is a second problem. Your invoice page needs a Delete button with an id, a Save button with a different colour, and a Pay button that is disabled until the invoice is approved. If the button component only knows about its own props, every new attribute means editing the component. You would end up with a long list of arguments that just repeat HTML attributes.

Blade solves both with anonymous components and the attribute bag. An anonymous component needs only a Blade file, and the attribute bag carries extra HTML attributes through to your markup. In this lesson you will learn both, and rebuild the status badge the simple way.

The Problem: Too Much Code for Small Pieces

This is the class-based badge from the Components lesson:

class StatusBadge extends Component
{
    public function __construct(public string $status = 'pending') {}

    public function label(): string
    {
        return match ($this->status) {
            'paid'    => 'Paid',
            'overdue' => 'Overdue',
            default   => 'Pending',
        };
    }

    public function render(): View|Closure|string
    {
        return view('components.status-badge');
    }
}

Nothing here needs a class. There is no database work, no service and no complicated logic. A component like this only needs a view file, and anonymous components are made for exactly that.

 

What Is an Anonymous Component?

An anonymous component is a Blade component with no PHP class. You create one file inside resources/views/components, and the file name becomes the tag:

resources/views/components/
    status-badge.blade.php        <x-status-badge>
    button.blade.php              <x-button>
    money.blade.php               <x-money>

Laravel finds these files on its own, with nothing to register. Use the same x- tag you already know. The difference is only in how the component is built, not in how it is used.

You can create the file by hand, or let Artisan do it with the --view option:

php artisan make:component Money --view

This creates only resources/views/components/money.blade.php and no class.

 

Defining Props with @props

A class-based component receives data through its constructor. An anonymous component has no constructor, so it declares its data with the @props directive at the top of the file.

Create resources/views/components/money.blade.php:

@props(['amount', 'currency' => '₹'])

<span {{ $attributes->merge(['class' => 'money']) }}>
    {{ $currency }} {{ number_format($amount) }}
</span>

The @props array works like this:

  • 'amount' is a required prop. There is no default, so the page must send it.
  • 'currency' => '₹' is an optional prop with a default value.

Every prop becomes a normal variable in the view. Use the component like this:

<x-money :amount="$invoice['total']" />

For an invoice total of 25000, the browser receives:

<span class="money">
    ₹ 25,000
</span>

As in the Components lesson, a colon in front of the attribute means a PHP expression, and no colon means plain text. Prop names in @props use camelCase, and the tag uses kebab-case, so a prop called showGst is written as show-gst in the tag.

 

Rebuilding the Status Badge Without a Class

Now replace the class-based badge. Delete app/View/Components/StatusBadge.php, and rewrite resources/views/components/status-badge.blade.php:

@props(['status' => 'pending'])

@php
    $label = match ($status) {
        'paid'    => 'Paid',
        'overdue' => 'Overdue',
        default   => 'Pending',
    };
@endphp

<span {{ $attributes->class(['badge', 'badge-' . $status]) }}>{{ $label }}</span>

The match expression moved into a @php block, and the class is gone. The pages that use the badge do not change at all:

<x-status-badge :status="$invoice['status']" />

Delete the old class when you switch. If both a class and a view exist for the same tag, Laravel uses the class first, and your new file would never run. The @php block is fine for a small label like this. If you find yourself writing a lot of PHP in it, that is the sign to go back to a class-based component.

 

The Attribute Bag: $attributes

In every component view, Laravel gives you a variable called $attributes. It holds every attribute written in the tag that is not a declared prop. This is the attribute bag.

Consider this tag:

<x-money :amount="25000" id="grand-total" class="font-bold" />

The attribute amount is declared in @props, so it becomes the variable $amount. The other two, id and class, are not props, so they go into $attributes. When you print the bag, they appear as HTML:

<span {{ $attributes }}>

becomes

<span id="grand-total" class="font-bold">

This means the component accepts any HTML attribute without knowing about it in advance: id, class, data-*, aria-*, disabled, Alpine directives and more. You only have to remember to print {{ $attributes }} on the root element, as the examples above do.

 

Merging Default Attributes

Printing the bag as it is gives you only what the page sent. Usually the component wants its own defaults too. The merge() method combines both.

Create resources/views/components/button.blade.php:

@props(['variant' => 'primary'])

<button {{ $attributes->merge(['type' => 'button', 'class' => 'btn btn-' . $variant]) }}>
    {{ $slot }}
</button>

The button has a default type of button, a base class, and a variant prop that changes the second class. Now use it on three pages:

<x-button>Save draft</x-button>

<x-button variant="danger" type="submit" id="delete-invoice" class="mt-4">
    Delete invoice
</x-button>

The first tag has no extra attributes, so you get the defaults. For the second, the browser receives:

<button type="submit" id="delete-invoice" class="btn btn-danger mt-4">
    Delete invoice
</button>

Notice two different behaviours:

  • The class attribute is combined. The page’s mt-4 is added after the component’s own classes, so the component keeps its base look while the page adds extras.
  • Every other attribute is replaced. The page sent type="submit", so it won over the default type="button".

This difference is intentional. Classes add up, and other attributes can be overridden by the page. Because variant is a declared prop, it never reaches the HTML. Only leftover attributes do.

 

Building Classes Conditionally

The class() method, used in the badge above, builds a class list from an array. Plain strings are always added, and an entry with a key is added only when its value is true:

<div {{ $attributes->class([
    'invoice-row',
    'invoice-row-overdue' => $status === 'overdue',
    'invoice-row-paid'    => $status === 'paid',
]) }}>

This is much cleaner than gluing strings together with ternary operators. The result still includes any class the page passed in, because class() works on the bag. You can chain it with merge() when you also need default attributes:

{{ $attributes->class(['btn'])->merge(['type' => 'button']) }}

You will use this a lot once Tailwind CSS arrives in a few lessons, because each element tends to carry many classes. The Blade code stays the same. Only the class names change.

 

Working with the Attribute Bag

The bag has several helper methods for cases where printing everything is not what you want:

{{-- Print only some attributes --}}
<span {{ $attributes->only(['id', 'class']) }}>

{{-- Print everything except some --}}
<span {{ $attributes->except(['class']) }}>

{{-- Check if an attribute was sent --}}
@if ($attributes->has('disabled'))
    ...
@endif

{{-- Read one value, with a default --}}
{{ $attributes->get('id', 'no-id') }}

{{-- Only attributes starting with a prefix --}}
<span {{ $attributes->whereStartsWith('data-') }}>

A common use is to send some attributes to an inner element and the rest to the outer one. For example, a form field component can place class on the wrapper and name, value and placeholder on the input. Forms get their own chapter later, so for now just remember that the bag can be split.

Attributes without a value, like disabled, work too. Write <x-button disabled>Pay now</x-button> and the attribute reaches the button.

 

Components in Folders and the index File

Folders work the same way as in class-based components, and the dot in the tag follows the path:

resources/views/components/
    invoice/
        row.blade.php             <x-invoice.row>

For a component that has related parts, you can create a folder and use a file named index.blade.php for the main piece. Take a card with a header:

resources/views/components/card/
    index.blade.php               <x-card>
    header.blade.php              <x-card.header>


<x-card>
    <x-card.header>Invoice 1001</x-card.header>

    <x-money :amount="25000" />
</x-card>

The card’s index.blade.php prints {{ $slot }} for its content, and each part can have its own file. This keeps a family of pieces together, and the tag names read naturally. You will build a card like this in the UI Kit lesson.

 

Sharing Parent Data with @aware

A child component normally knows nothing about its parent. Sometimes that is a problem. Imagine a menu where the parent sets a colour, and every menu item should use it without repeating the colour on each item. The @aware directive lets a child read a prop from its parent:

{{-- components/menu/index.blade.php --}}
@props(['color' => 'gray'])

<ul {{ $attributes->class(['menu', 'menu-' . $color]) }}>
    {{ $slot }}
</ul>


{{-- components/menu/item.blade.php --}}
@aware(['color' => 'gray'])

<li {{ $attributes->class(['menu-item', 'menu-item-' . $color]) }}>
    {{ $slot }}
</li>


<x-menu color="blue">
    <x-menu.item>Invoices</x-menu.item>
    <x-menu.item>Clients</x-menu.item>
</x-menu>

Both items now get the blue class. @aware only sees values that the page explicitly sent to the parent. If the page wrote <x-menu> with no colour, the parent’s default gray is not passed on, so the child uses its own default. Do not lean on @aware too much. Explicit props are easier to follow.

 

Class-Based or Anonymous?

You now have both kinds of component, so here is a way to decide:

  • Use an anonymous component when the piece is mainly HTML with a few props. Buttons, badges, money labels, cards and menu items fit here. This should be your default.
  • Use a class-based component when you need real PHP logic, such as calculations, helper methods, dependency injection from the container, or data that needs preparing before the view.
  • Start anonymous. If the @php block grows, move it into a class later. The tag stays the same, so pages never notice.

 

Common Mistakes

Mistake 1: Forgetting to Declare a Prop

{{-- status-badge.blade.php has no @props --}}
<span>{{ $status }}</span>

With no @props, the attribute status is not turned into a variable. It stays in the bag, and the view fails with:

ErrorException: Undefined variable $status

Declare every piece of data you use in @props.

 

Mistake 2: Forgetting a Required Prop

@props(['amount', 'currency' => '₹'])


<x-money />

The amount prop has no default and the page did not send it, so Blade stops with Undefined variable $amount. Give the prop a default if it is optional, or make sure every page sends it.

 

Mistake 3: Not Printing $attributes

<button class="btn">{{ $slot }}</button>

The page sends id="delete-invoice" and disabled, and nothing happens. There is no error. The attributes were collected in the bag, and you never printed it. Always add {{ $attributes }} or a merge() call on the root element.

 

Mistake 4: Expecting Other Attributes to Combine Like class

{{ $attributes->merge(['type' => 'button']) }}

A page that sends type="submit" replaces the default completely. Only class is combined. If you want to combine another attribute, use prepends() for that attribute, for example $attributes->merge(['data-controller' => $value])->prepends(...). In practice, most components need only the default behaviour.

 

Mistake 5: Putting @props in the Wrong Place

<span>{{ $status }}</span>

@props(['status' => 'pending'])

@props must come before you use the variables, so keep it at the very top of the file. If it is placed lower, the variable does not exist yet when the markup is printed.

 

Mistake 6: Leaving the Old Class Behind

After converting StatusBadge to an anonymous component, you edit the new view and nothing changes. The old class file is still in app/View/Components, and Laravel keeps using it. Delete the class when you move to an anonymous version.

 

Quick Summary

  • An anonymous component has no PHP class. One file in resources/views/components becomes a tag like <x-money>.
  • Create one with php artisan make:component Money --view.
  • Declare data at the top of the file with @props(['amount', 'currency' => '₹']). A prop with no default is required.
  • Props use camelCase in @props and kebab-case in the tag. Use a colon for PHP expressions.
  • Everything that is not a prop goes into $attributes, so print it on the root element.
  • merge() adds default attributes. class is combined, and every other attribute is replaced by the page.
  • class() builds a class list from an array and supports conditions.
  • Helpers like only(), except(), has(), get() and whereStartsWith() work with parts of the bag.
  • Folders create dotted tags, and index.blade.php makes the main component of a folder.
  • @aware lets a child read a prop from its parent, but explicit props are easier to follow.
  • Start with anonymous components, and move to a class when you need real PHP logic.

 

What’s Next

Your components now accept any attribute and merge their own classes, but the pages still look plain. In the next lesson, Tailwind CSS & Alpine.js with Vite, you will set up a proper frontend build, style your layout with Tailwind and add small interactions with Alpine.js. The components you wrote here will carry those classes with no change to their structure.

Frequently Asked Questions

It is a Blade component that has only a view file and no PHP class. You place the file in resources/views/components, and the file name becomes the tag, so button.blade.php is used as x-button. It is the simplest way to reuse a piece of HTML with props and slots.
It is the attribute bag, an object that holds every HTML attribute passed to the component that is not a declared prop. Printing it on the root element sends those attributes, such as id, class and data attributes, to the final HTML. It also has methods like merge, class, only and except.
It does both, depending on the attribute. The class attribute is combined, so the component’s classes and the page’s classes appear together. For every other attribute, such as type or id, the value from the page replaces the default value from the component.
Run php artisan make:component with the component name and add the view option. This creates only the Blade file in resources/views/components and no class. You can also create the file by hand, because Laravel finds anonymous components automatically.
Props are the values you list in the props directive, and each one becomes a variable in the view. Attributes are everything else written in the tag, and they are collected in the attribute bag. Use props for data the component needs to decide what to show, and attributes for plain HTML attributes that should pass through.

Share this tutorial