Livewire

A component in Livewire is any page element where we have server-side logic and presentation.

Components are used from within Laravel views and are capable of being easily reused throughout an entire application, encapsulating all their complexity within a single tag.

In Livewire you can make simple and complex components but they will almost always have two different parts: controller and view, although you can also make “inline” components, in which both the logic and the presentation are defined within the controller.

The controller

Which contains the PHP logic used to define the properties and access data handled by this component. The controller consists of a class, object-oriented programming, where we can define component properties through public properties of the class itself.

The controller contains a render() method that calls the view that will be in charge of displaying the visual part of the component.

Here we can see an example controller in Livewire:

namespace App\Http\Livewire; use App\Models\Country; use Livewire\Component; class CountrySearch extends Component { public $keyword = ”; public function render() { return view(‘livewire.country-search’)->with(); } }

the view

It consists of a file created with Laravel’s Blade template system. In the view we can use all the public properties of the component and through directives talk to the controller, changing its properties or executing its methods.

When the controller’s properties change, the render method is called again, which takes care of refreshing the view, closing the cycle of changes and updates that provides that dynamic Livewire experience.

A view of a Livewire component looks like this:

@endforeach

< /div>

Inside the view we find an input that has the directive “wire:model”. This produces a data link, or “data binding”, with the controller. The controller’s public property called “keyword” will be bound to what the user types into the text field. Therefore, if the user writes anything in the , the property will change and with it the call of the render method and the corresponding refresh of the view.

Using Livewire Components

To use a Livewire component we call it from a Blade view. It is achieved with the @livewire directive of Blade, indicating the name of the component with “Kebab Case”.

@livewire(‘country-search’)

As of Laravel 7, components managed through classes were introduced, something that Livewire took advantage of to introduce an alternative syntax for the use of components.

Both notations produce the rendering of the same component and can be mixed in the same Blade view, and of course in the whole application, as long as we are in Laravel 7 onwards.

Pin It
Loading Facebook Comments ...
Loading Disqus Comments ...