🎓 A1Learner
🔍
0 of 50 lessons completed

Laravel Blade Components

A Blade component is a reusable piece of a view, such as an alert box. It is defined once and used in many views.

Make a component

Artisan creates the component class and its view.

php artisan make:component Alert

The component view

A component is defined once and used in many views. The @props line sets the default type to info.

@props(['type' => 'info'])
<div class="alert alert-{{ $type }}">{{ $slot }}</div>

Use the component

The view places the component and passes the message in the slot.

<x-alert type="success">Book saved.</x-alert>

Example

Route::get('/notice', fn () => view('notice'));

<x-alert type="success">Book saved.</x-alert>

@props(['type' => 'info'])
<div class="alert alert-{{ $type }}">{{ $slot }}</div>

Key points

  • Blade component: a reusable piece of a view, defined once and used in many views.
  • Use <x-alert> to place the alert component in a view.
  • Use the slot to pass the content that goes inside the component.
  • Use an attribute, such as type="success", to pass a value into the component.

In this example, the route returns the notice view. The notice view places the alert component with the message Book saved. The component view prints a div with the type and the message. The page shows one alert box.

Note

A component class and its view share one name, such as Alert.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What goes inside a component's slot?