Overview
The Livewire component system provides full server-side reactivity, allowing you to build dynamic interfaces without writing JavaScript. Components automatically sync state between server and client.
Class: Lyger\Livewire\Component
Base class for all Livewire components with reactive properties and lifecycle hooks.
Creating a Component
use Lyger\Livewire\Component;
class Counter extends Component
{
public int $count = 0;
public function increment()
{
$this->count++;
}
public function render(): string
{
return view('counter', ['count' => $this->count]);
}
}
Lifecycle Methods
mount()
Called when the component is first created.
Optional parameters passed to the component
public function mount(int $userId): void
{
$this->userId = $userId;
$this->loadUser();
}
render()
Renders the component view. Must be implemented by all components.
The rendered HTML of the component
abstract public function render(): string;
Property Management
getPublicProperties()
Returns all public properties for JavaScript synchronization.
Array of public property names and values
public function getPublicProperties(): array
Example:
class UserProfile extends Component
{
public string $name = 'John';
public string $email = 'john@example.com';
protected string $password = 'secret'; // Not included
// getPublicProperties() returns: ['name' => 'John', 'email' => 'john@example.com']
}
get()
Retrieves a protected property value.
Default value if property doesn’t exist
protected function get(string $key, $default = null)
set()
Sets a property value and tracks it for updates.
protected function set(string $key, $value): void
Method Calling
callMethod()
Executes a method on the component and returns effects.
Parameters to pass to the method
Contains ‘effect’, ‘data’, or ‘error’ keys
public function callMethod(string $method, array $params = []): array
Example:
$component->callMethod('increment', []);
// Returns: ['effect' => ['properties' => ['count' => 1]], 'data' => null]
Validation
validate()
Validates component properties against rules.
Validated data on success
Thrown when validation fails
protected function validate(array $rules, array $messages = []): array
Example:
public function submitForm()
{
$validated = $this->validate([
'email' => 'required|email',
'password' => 'required|min:8',
], [
'email.required' => 'Email is required',
]);
// Process validated data...
}
addError()
Manually adds an error message for a field.
protected function addError(string $field, string $message): void
Events
emit()
Emits an event to other components.
Event parameters (variadic)
protected function emit(string $event, ...$params): array
Example:
public function userUpdated()
{
$this->emit('user-updated', $this->userId, $this->name);
}
emitUp()
Emits an event to parent components only.
protected function emitUp(string $event, ...$params): array
dispatchBrowserEvent()
Dispatches a custom browser event for JavaScript to listen to.
protected function dispatchBrowserEvent(string $event, array $data = []): array
Example:
public function showNotification()
{
$this->dispatchBrowserEvent('notify', [
'type' => 'success',
'message' => 'Operation completed!',
]);
}
Navigation
redirect()
Redirects to a URL.
protected function redirect(string $url): array
redirectToRoute()
Redirects to a named route with parameters.
protected function redirectToRoute(string $route, array $params = []): array
Example:
public function saveUser()
{
// Save user...
return $this->redirectToRoute('/users/{id}', ['id' => $this->userId]);
}
refresh()
Refreshes the component.
protected function refresh(): array
File Uploads
validateFile()
Validates an uploaded file.
protected function validateFile(string $field, array $rules): array
Example:
public function uploadAvatar()
{
$this->validateFile('avatar', [
'avatar' => 'required|image|max:2048',
]);
// Process file...
}
Utility Methods
reset()
Resets component properties to default values.
Specific properties to reset (variadic). If empty, resets all.
protected function reset(...$properties): void
Example:
public function clearForm()
{
$this->reset('name', 'email'); // Reset specific fields
// or
$this->reset(); // Reset all properties
}
user()
Gets the currently authenticated user.
User data array or null if not authenticated
protected function user(): ?array
isAuthenticated()
Checks if a user is authenticated.
True if authenticated, false otherwise
protected function isAuthenticated(): bool
Traits
WithEvents
Provides event listener functionality.
use Lyger\Livewire\Component;
use Lyger\Livewire\WithEvents;
class MyComponent extends Component
{
use WithEvents;
protected array $listeners = [
'user-updated' => 'onUserUpdated',
];
public function onUserUpdated($userId)
{
// Handle event...
}
}
WithFileUploads
Provides file upload handling.
use Lyger\Livewire\WithFileUploads;
class UploadForm extends Component
{
use WithFileUploads;
public function handleUpload()
{
$file = $this->request->file('document');
$path = $this->upload('document', $file);
// $path = '/uploads/abc123_document.pdf'
}
}
Adds pagination functionality to components.
use Lyger\Livewire\WithPagination;
class UserList extends Component
{
use WithPagination;
protected int $perPage = 20;
public function render(): string
{
$users = User::paginate($this->perPage, $this->page);
return view('users.list', compact('users'));
}
}
Methods:
nextPage(): Go to next page
previousPage(): Go to previous page
gotoPage(int $page): Jump to specific page
WithSearch
Adds search functionality with query filtering.
use Lyger\Livewire\WithSearch;
class SearchableUsers extends Component
{
use WithSearch;
protected array $searchable = ['name', 'email'];
public function render(): string
{
$query = User::query();
$query = $this->applySearch($query);
$users = $query->get();
return view('users.search', compact('users'));
}
}
The updatingSearch() lifecycle hook automatically resets pagination to page 1 when search changes.
Manager Class
Lyger\Livewire\Manager
Manages component registration and request handling.
register()
Registers a component class.
Manager::register('counter', Counter::class);
get()
Gets a component instance by name.
$component = Manager::get('counter');
handle()
Handles incoming Livewire AJAX requests.
JSON response with component data
public static function handle(Request $request): Response
Complete Example
use Lyger\Livewire\Component;
use Lyger\Livewire\WithPagination;
class TodoList extends Component
{
use WithPagination;
public array $todos = [];
public string $newTodo = '';
protected int $perPage = 10;
public function mount()
{
$this->loadTodos();
}
public function addTodo()
{
$this->validate([
'newTodo' => 'required|min:3',
]);
$this->todos[] = [
'id' => uniqid(),
'text' => $this->newTodo,
'completed' => false,
];
$this->newTodo = '';
$this->emit('todo-added');
}
public function toggleTodo($id)
{
foreach ($this->todos as &$todo) {
if ($todo['id'] === $id) {
$todo['completed'] = !$todo['completed'];
break;
}
}
}
private function loadTodos()
{
// Load from database...
}
public function render(): string
{
return view('todos.list', [
'todos' => array_slice($this->todos,
($this->page - 1) * $this->perPage,
$this->perPage
),
]);
}
}