Skip to content

Components

Laravel Livewire Documentation Reference

Since Magewire is heavily inspired by Laravel Livewire, many concepts are either identical or very similar. To avoid duplicating documentation, this page only covers Magewire-specific and platform-specific details. For all general concepts and in-depth explanations, you can refer to the corresponding Laravel Livewire documentation.

Livewire Reference

Creating components

Creating a basic Magewire component takes just a few minutes and requires only two or three files, depending on whether you already have a layout handle. At its core, a Magewire component consists of two main files: a PHP class that handles the logic and a template responsible for rendering the HTML on the frontend.

In the following example, we assume you are using layout XML to inject a Magewire component onto a page. For more advanced use cases, we recommend exploring the in-depth documentation, where concepts like the resolver mechanism will most likely play a role.

1. Create a Component class

Create a new component class:

File: Magewire/Counter.php
<?php

namespace Vendor\Module\Magewire;

class Counter extends \Magewirephp\Magewire\Component
{
    public int $count = 0;

    public function increment(): void
    {
        $this->count++;
    }
}

Note: It is advisable to keep your components inside the Magewire root directory of your module, either as direct children or nested within subdirectories.

2. Create a Template File

Now, create the corresponding template file:

File: view/frontend/templates/magewire/counter.phtml
<div>
    Counter: <?= $magewire->count ?>

    <button wire:click="increment">
        Increase
    </button>
</div>

Note: Every Magewire component binds its state to the first HTML element in its template. This means you must always wrap your component's content in a root HTML element, such as a <div>, to ensure proper functionality.

3. Inject onto a page

To render the component, add the following to your layout handle:

File: view/frontend/layout/page_handle.xml
<referenceBlock name="content">
    <block name="counter.block" template="Vendor_Module::magewire/counter.phtml">
        <arguments>
            <argument name="magewire" xsi:type="object">
                Vendor\Module\Magewire\Counter
            </argument>
        </arguments>
    </block>
</referenceBlock>

Note: This is the standard method for injecting a Magewire component into your page. However, alternatives exist through component resolvers, allowing more flexible integration. You can even create a custom resolver to fit specific requirements.

4. Test it out

Counter

Clear the Magento cache and navigate to the relevant page:

bin/magento cache:flush