Livewire Volt Has A New Class-based API

Published on

The Laravel team recently released Volt, which allows you to build full Livewire components right in your Blade views. Initially, it was released with a functional syntax. You can import Volt's functions and wrap your Livewire functionality for state, computed properties, actions, etc. in those.

For example, a simple component for creating a post using the functional syntax:

1<?php
2 
3use App\Models\Post;
4use function Livewire\Volt\{state};
5use function Livewire\Volt\{rules};
6 
7state([
8 'title' => '',
9 'content' => '',
10]);
11 
12rules([
13 'title' => ['required', 'max:250'],
14 'content' => ['required', 'max:10000'],
15]);
16 
17$save = function () {
18 $this->validate();
19 
20 Post::create([
21 'title' => $this->title,
22 'content' => $this->content,
23 ]);
24 
25 return redirect('/posts');
26}
27?>
28 
29<form wire:submit="save">
30 <div>
31 <label>Title</label>
32 <input wire:model="title" type="text" />
33 </div>
34 <div>
35 <label>Content</label>
36 <textarea wire:model="content"></textarea>
37 </div>
38 
39 <button>Save</button>
40</form>

As of today, the Laravel team has released v1.0-beta.3 which introduces a new class-based syntax for Volt components. This allows you to write Livewire components using the more traditional syntax you're used to, but still all inside your Blade files.

For example, the same create post component written with the new class-based syntax:

1<?php
2 
3use App\Models\Post;
4use Livewire\Volt\Component;
5use Livewire\Attributes\Rule;
6 
7new class extends Component
8{
9 #[Rule(['required', 'max:250'])]
10 public $title = '';
11 
12 #[Rule(['required', 'max:10000'])]
13 public $content = '';
14 
15 public function save() {
16 $this->validate();
17 
18 Post::create([
19 'title' => $this->title,
20 'content' => $this->content,
21 ]);
22 
23 return redirect('/posts');
24 }
25}
26?>
27 
28<form wire:submit="save">
29 <div>
30 <label>Title</label>
31 <input wire:model="title" type="text" />
32 </div>
33 <div>
34 <label>Content</label>
35 <textarea wire:model="content"></textarea>
36 </div>
37 
38 <button>Save</button>
39</form>

What do you think? Do you prefer the functional syntax or the more traditional class-based syntax? Personally, I like the class-based syntax a little more, but it's awesome to see the Laravel team providing multiple ways for people to build functionality!