### Install Livewire and Assets
Source: https://context7.com/livewire/docs/llms.txt
Use Composer to install the package and include the required assets in your Blade layout.
```bash
composer require livewire/livewire
```
```html
...
@livewireStyles
...
@livewireScripts
```
--------------------------------
### Define Computed Properties
Source: https://context7.com/livewire/docs/llms.txt
Use the get[Name]Property pattern to define properties that are computed on-demand and cached.
```php
class ShowPost extends Component
{
public $postId;
// Define computed property with get[Name]Property pattern
public function getPostProperty()
{
return Post::find($this->postId);
}
public function deletePost()
{
// Access as $this->post
$this->post->delete();
}
}
```
--------------------------------
### Generate and Define Components
Source: https://context7.com/livewire/docs/llms.txt
Use artisan commands to scaffold components and define the PHP class structure.
```bash
# Create a basic component
php artisan make:livewire ShowPosts
# Create component in a sub-folder
php artisan make:livewire Post/Show
# Create an inline component (no separate Blade file)
php artisan make:livewire ShowPosts --inline
# Create component with a test file
php artisan make:livewire ShowPosts --test
```
```php
// app/Http/Livewire/ShowPosts.php
namespace App\Http\Livewire;
use Livewire\Component;
class ShowPosts extends Component
{
public function render()
{
return view('livewire.show-posts');
}
}
```
--------------------------------
### Render Full-Page Components
Source: https://context7.com/livewire/docs/llms.txt
Configure component rendering with layouts or sections.
```php
class ShowPost extends Component
{
public Post $post;
// Route model binding works automatically
public function mount(Post $post)
{
$this->post = $post;
}
public function render()
{
return view('livewire.show-post')
->layout('layouts.app')
->slot('main');
// Or with extends
return view('livewire.show-post')
->extends('layouts.app')
->section('content');
}
}
```
--------------------------------
### Livewire Component Lifecycle Hooks
Source: https://context7.com/livewire/docs/llms.txt
Implement lifecycle hooks like `boot`, `booted`, `mount`, `hydrate`, `dehydrate`, `updating`, and `updated` to manage component behavior at different stages.
```php
class HelloWorld extends Component
{
public $foo;
// Runs on every request, immediately after instantiation
public function boot()
{
//
}
// Runs on every request, after mount or hydrate
public function booted()
{
//
}
// Runs once on initial page load only
public function mount()
{
//
}
// Runs on subsequent requests, after hydration
public function hydrate()
{
//
}
// Runs before dehydration on subsequent requests
public function dehydrate()
{
//
}
// Property-specific hooks
public function hydrateFoo($value)
{
//
}
public function dehydrateFoo($value)
{
//
}
// Runs before/after any property update via wire:model
public function updating($name, $value)
{
//
}
public function updated($name, $value)
{
//
}
// Property-specific update hooks
public function updatingFoo($value)
{
//
}
public function updatedFoo($value)
{
//
}
}
```
--------------------------------
### Create File Upload Forms and Progress Indicators
Source: https://context7.com/livewire/docs/llms.txt
Provides HTML templates for file inputs, previews, and AlpineJS-based progress tracking.
```html
```
--------------------------------
### Deferred Component Loading
Source: https://context7.com/livewire/docs/llms.txt
Use wire:init to defer the loading of a component until after the initial page render, improving perceived performance. Set a public property to true to trigger data loading.
```php
class ShowPosts extends Component
{
public $readyToLoad = false;
public function loadPosts()
{
$this->readyToLoad = true;
}
public function render()
{
return view('livewire.show-posts', [
'posts' => $this->readyToLoad ? Post::all() : [],
]);
}
}
```
--------------------------------
### Define Full-Page Component Routes
Source: https://context7.com/livewire/docs/llms.txt
Register Livewire components as route controllers in web.php.
```php
// routes/web.php
Route::get('/posts', ShowPosts::class);
Route::get('/post/{post}', ShowPost::class);
```
--------------------------------
### Test Livewire Components
Source: https://context7.com/livewire/docs/llms.txt
Use PHPUnit and Livewire testing utilities to verify component state, events, and redirects.
```php
use Livewire\Livewire;
class CreatePostTest extends TestCase
{
/** @test */
public function can_create_post()
{
$this->actingAs(User::factory()->create());
Livewire::test(CreatePost::class)
->set('title', 'My Post')
->call('create');
$this->assertTrue(Post::whereTitle('My Post')->exists());
}
/** @test */
public function title_is_required()
{
Livewire::test(CreatePost::class)
->set('title', '')
->call('create')
->assertHasErrors(['title' => 'required']);
}
/** @test */
public function can_pass_initial_data()
{
Livewire::test(ShowPost::class, ['post' => $post])
->assertSet('post.title', 'Expected Title');
}
/** @test */
public function can_test_with_query_params()
{
Livewire::withQueryParams(['search' => 'foo'])
->test(SearchPosts::class)
->assertSet('search', 'foo');
}
/** @test */
public function redirects_after_creation()
{
Livewire::test(CreatePost::class)
->set('title', 'foo')
->call('create')
->assertRedirect('/posts');
}
/** @test */
public function emits_event_when_created()
{
Livewire::test(CreatePost::class)
->call('create')
->assertEmitted('postCreated');
}
/** @test */
public function page_contains_component()
{
$this->get('/posts/create')
->assertSeeLivewire('create-post');
}
}
```
--------------------------------
### Embedding and Keying Nested Components
Source: https://context7.com/livewire/docs/llms.txt
Demonstrates embedding a single component and multiple components within a loop, highlighting the necessity of unique keys for dynamic lists.
```html
User Details:
Name: {{ $user->name }}
Email: {{ $user->email }}
User Notes:
@livewire('add-user-note', ['user' => $user])
@foreach ($users as $user)
@livewire('user-profile', ['user' => $user], key($user->id))
@endforeach
@foreach ($users as $user)
@endforeach
@foreach ($users as $user)
@endforeach
```
--------------------------------
### Emit and Listen to Component Events in Livewire
Source: https://context7.com/livewire/docs/llms.txt
Use `emit`, `emitUp`, `emitTo`, and `emitSelf` to communicate between components. Define listeners using the `$listeners` property or `getListeners` method.
```php
class CreatePost extends Component
{
public function save()
{
$post = Post::create($this->validate());
// Emit to all components
$this->emit('postAdded', $post->id);
// Emit only to parent components
$this->emitUp('postAdded');
// Emit to specific component type
$this->emitTo('post-list', 'postAdded');
// Emit only to self
$this->emitSelf('postSaved');
}
}
// Listening component
class ShowPosts extends Component
{
public $postCount;
protected $listeners = ['postAdded' => 'incrementPostCount'];
// Or dynamic listeners
protected function getListeners()
{
return ['postAdded' => 'incrementPostCount'];
}
public function incrementPostCount($postId)
{
$this->postCount = Post::count();
}
}
```
--------------------------------
### Manage Public Properties
Source: https://context7.com/livewire/docs/llms.txt
Public properties are synchronized between the server and the view. Use mount() for initialization and reset methods to clear state.
```php
class HelloWorld extends Component
{
public $message = 'Hello World!';
public $search = '';
public $isActive = true;
public function mount()
{
// Initialize properties
$this->message = 'Hello World!';
// Or use fill() for multiple properties
$this->fill(['message' => 'Hello!', 'search' => '']);
}
public function resetFilters()
{
// Reset specific properties to initial values
$this->reset('search');
$this->reset(['search', 'isActive']);
// Reset all except specified
$this->resetExcept('search');
}
}
```
```html
{{ $message }}
```
--------------------------------
### Listen to Browser Events with Vanilla JavaScript and AlpineJS
Source: https://context7.com/livewire/docs/llms.txt
Capture browser events dispatched from Livewire using standard `window.addEventListener` or AlpineJS's `@event.window` directive. Access event details via `event.detail`.
```html
```
--------------------------------
### Implement Pagination in Livewire
Source: https://context7.com/livewire/docs/llms.txt
Uses the WithPagination trait to manage database result sets and custom paginator configurations.
```php
use Livewire\WithPagination;
class ShowPosts extends Component
{
use WithPagination;
public $search = '';
// Use Bootstrap theme instead of Tailwind
protected $paginationTheme = 'bootstrap';
// Reset pagination when search changes
public function updatingSearch()
{
$this->resetPage();
}
public function render()
{
return view('livewire.show-posts', [
'posts' => Post::where('title', 'like', '%'.$this->search.'%')
->paginate(10),
]);
}
}
// Multiple paginators
class ListPostComments extends Component
{
use WithPagination;
public Post $post;
public function render()
{
return view('livewire.list-comments', [
// Use custom page name for multiple paginators
'comments' => $this->post->comments()
->paginate(10, ['*'], 'commentsPage'),
]);
}
}
```
--------------------------------
### Synchronize Component Properties with Query String
Source: https://context7.com/livewire/docs/llms.txt
Use the $queryString property to map component properties to URL query parameters. Specify 'except' to define default values and 'as' for URL aliases.
```php
class SearchPosts extends Component
{
public $search = '';
public $page = 1;
protected $queryString = [
'search' => ['except' => ''],
'page' => ['except' => 1],
];
// With URL aliases
protected $queryString = [
'search' => ['except' => '', 'as' => 's'],
'page' => ['except' => 1, 'as' => 'p'],
];
// Results in URL: ?s=Livewire&p=2
public function render()
{
return view('livewire.search-posts', [
'posts' => Post::where('title', 'like', '%'.$this->search.'%')->get(),
]);
}
}
```
--------------------------------
### Initialize Component Data Loading
Source: https://context7.com/livewire/docs/llms.txt
The wire:init directive on a container element calls the specified component method upon initialization. This is useful for deferring data loading.
```html
@if($readyToLoad)
@foreach ($posts as $post)
{{ $post->title }}
@endforeach
@else
Loading posts...
@endif
```
--------------------------------
### Emit Events from Livewire Template and Listen in JavaScript
Source: https://context7.com/livewire/docs/llms.txt
Trigger Livewire events directly from HTML templates using `$emit`, `$emitUp`, and `$emitTo`. Listen for these events in JavaScript using `Livewire.on()`.
```html
```
--------------------------------
### Handle File Uploads in Livewire
Source: https://context7.com/livewire/docs/llms.txt
Implements the WithFileUploads trait for server-side file processing and validation.
```php
use Livewire\WithFileUploads;
class UploadPhoto extends Component
{
use WithFileUploads;
public $photo;
public $photos = []; // For multiple uploads
public function updatedPhoto()
{
// Real-time validation
$this->validate([
'photo' => 'image|max:1024', // 1MB Max
]);
}
public function save()
{
$this->validate([
'photo' => 'image|max:1024',
]);
// Store file
$this->photo->store('photos');
// Store with custom name
$this->photo->storeAs('photos', 'avatar.png');
// Store to S3
$this->photo->store('photos', 's3');
// Store publicly
$this->photo->storePublicly('photos', 's3');
}
public function saveMultiple()
{
$this->validate([
'photos.*' => 'image|max:1024',
]);
foreach ($this->photos as $photo) {
$photo->store('photos');
}
}
}
```
--------------------------------
### Render Components in Blade
Source: https://context7.com/livewire/docs/llms.txt
Use tag syntax or Blade directives to render components, optionally passing parameters.
```html
@livewire('show-posts')
@livewire('show-post', ['post' => $post])
```
```php
// Receiving parameters in the component
class ShowPost extends Component
{
public $post; // Automatically assigned from parameter
// Or use mount() for custom handling
public function mount($post)
{
$this->title = $post->title;
$this->content = $post->content;
}
}
```
--------------------------------
### Livewire Loading States Directives
Source: https://context7.com/livewire/docs/llms.txt
Utilize `wire:loading` and `wire:loading.remove` to conditionally display elements during network requests. Target specific actions or model updates using `wire:target`.
```html
Processing Payment...
Ready to checkout
Processing...
Loading...
Updating Bob...
Updating quantity...
Loading...
Loading...
...
...
```
--------------------------------
### Common Testing Assertions
Source: https://context7.com/livewire/docs/llms.txt
Reference for available methods when testing component interactions and state.
```php
Livewire::test('component-name', ['param' => $value])
->set('property', 'value') // Set property value
->toggle('booleanProperty') // Toggle boolean
->call('method') // Call component method
->call('method', 'arg1', 'arg2') // Call with arguments
->emit('event') // Emit event
->assertSet('property', 'value') // Assert property value
->assertNotSet('property', 'value') // Assert property not value
->assertCount('array', 5) // Assert array count
->assertSee('text') // Assert text visible
->assertDontSee('text') // Assert text not visible
->assertSeeHtml('
Title
') // Assert HTML present
->assertEmitted('event') // Assert event emitted
->assertNotEmitted('event') // Assert event not emitted
->assertHasErrors(['field']) // Assert validation errors
->assertHasNoErrors(['field']) // Assert no validation errors
->assertRedirect('/path') // Assert redirect
->assertNoRedirect() // Assert no redirect
->assertViewIs('view-name') // Assert current view
->assertStatus(200); // Assert HTTP status
```
--------------------------------
### View for Eloquent Model Binding
Source: https://context7.com/livewire/docs/llms.txt
Use dot notation in wire:model to bind inputs to model properties.
```html
```
--------------------------------
### Handling Redirects After Actions
Source: https://context7.com/livewire/docs/llms.txt
Return standard Laravel redirect responses from component actions to navigate users to different pages after an action is completed.
```php
class ContactForm extends Component
{
public $email;
public function addContact()
{
Contact::create(['email' => $this->email]);
// Standard redirects work
return redirect()->to('/contact-form-success');
// All Laravel redirect methods supported
return redirect('/foo');
return redirect()->route('contacts.index');
}
}
```
--------------------------------
### Define Component Actions
Source: https://context7.com/livewire/docs/llms.txt
Methods defined in a Livewire component can be triggered from the view. Dependency injection is supported for method parameters.
```php
class ShowPost extends Component
{
public Post $post;
public $count = 0;
public function like()
{
$this->post->addLikeBy(auth()->user());
}
public function increment()
{
$this->count++;
}
public function addTodo($id, $name)
{
// Parameters passed from the view
Todo::create(['id' => $id, 'name' => $name]);
}
// With dependency injection
public function addTodo(TodoService $todoService, $id, $name)
{
$todoService->create($id, $name);
}
}
```
--------------------------------
### Nesting Livewire Components
Source: https://context7.com/livewire/docs/llms.txt
Embed Livewire components within others using the @livewire directive or tag syntax. Ensure unique keys are provided for components rendered within loops.
```php
class UserDashboard extends Component
{
public User $user;
}
```
--------------------------------
### Implement Data Binding with wire:model
Source: https://context7.com/livewire/docs/llms.txt
Use wire:model to bind form inputs to component properties, supporting modifiers like debounce, lazy, and defer.
```php
class ContactForm extends Component
{
public $name;
public $email;
public $form = ['name' => '', 'email' => ''];
}
```
```html
```
--------------------------------
### Displaying Flash Messages
Source: https://context7.com/livewire/docs/llms.txt
Use Laravel's session flash system to display temporary messages to users. Flash messages persist through a single redirect.
```php
class UpdatePost extends Component
{
public Post $post;
public function update()
{
$this->validate();
$this->post->save();
session()->flash('message', 'Post successfully updated.');
}
public function updateAndRedirect()
{
$this->post->save();
// Flash persists through redirect
session()->flash('message', 'Post updated!');
return redirect()->to('/posts');
}
}
```
--------------------------------
### Dispatch Browser Events from Livewire
Source: https://context7.com/livewire/docs/llms.txt
Dispatch custom browser events from your Livewire components using `dispatchBrowserEvent`. These events can be caught by JavaScript listeners.
```php
class NameForm extends Component
{
public $name;
public function save()
{
$this->validate();
// Dispatch browser event
$this->dispatchBrowserEvent('name-updated', ['newName' => $this->name]);
}
}
```
--------------------------------
### Register JavaScript Lifecycle Hooks
Source: https://context7.com/livewire/docs/llms.txt
Hooks into Livewire component and element events within the browser.
```html
```
--------------------------------
### Trigger Actions and Events in View
Source: https://context7.com/livewire/docs/llms.txt
Use wire: directives to bind browser events to component methods and apply modifiers like debounce or prevent.
```html
Only fires if clicked directly
```
--------------------------------
### Bind Component Property to Search Input
Source: https://context7.com/livewire/docs/llms.txt
Use wire:model to bind an input element's value to a component property, enabling two-way data binding for search functionality.
```html
@foreach($posts as $post)
{{ $post->title }}
@endforeach
```
--------------------------------
### Authorize Component Actions
Source: https://context7.com/livewire/docs/llms.txt
Use the AuthorizesRequests trait to authorize actions within a Livewire component.
```php
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class EditPost extends Component
{
use AuthorizesRequests;
public Post $post;
public function mount(Post $post)
{
$this->post = $post;
}
public function save()
{
$this->authorize('update', $this->post);
$this->post->update(['title' => $this->title]);
}
}
```
--------------------------------
### Bind Eloquent Models
Source: https://context7.com/livewire/docs/llms.txt
Directly bind form inputs to Eloquent model properties to simplify data persistence.
```php
use App\Models\Post;
class PostForm extends Component
{
public Post $post;
protected $rules = [
'post.title' => 'required|string|min:6',
'post.content' => 'required|string|max:500',
];
public function save()
{
$this->validate();
$this->post->save();
}
}
```
--------------------------------
### Implement Form Validation
Source: https://context7.com/livewire/docs/llms.txt
Define validation rules, custom messages, and attributes within the component. Use validate() or validateOnly() to trigger checks.
```php
class ContactForm extends Component
{
public $name;
public $email;
protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
];
protected $messages = [
'email.required' => 'The Email Address cannot be empty.',
'email.email' => 'The Email Address format is not valid.',
];
protected $validationAttributes = [
'email' => 'email address'
];
// Real-time validation on property update
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
public function submit()
{
$validatedData = $this->validate();
Contact::create($validatedData);
}
// Dynamic rules
protected function rules()
{
return [
'email' => ['required', 'email', 'not_in:' . auth()->user()->email],
];
}
// Manual error handling
public function save()
{
$this->addError('email', 'The email field is invalid.');
$this->resetErrorBag();
$this->resetValidation('email');
}
}
```
--------------------------------
### Display Paginated Results in Blade
Source: https://context7.com/livewire/docs/llms.txt
Renders paginated data and navigation links within a Blade view.
```html
```
--------------------------------
### Rendering Flash Messages in Blade
Source: https://context7.com/livewire/docs/llms.txt
Check for the existence of a session flash key and display its content within a Blade view. This is commonly used for success or error messages.
```html
```
--------------------------------
### Automatic Component Refresh with Polling
Source: https://context7.com/livewire/docs/llms.txt
Utilize the wire:poll directive to automatically refresh a component's content at specified intervals. The default interval is 2 seconds.
```html
Current time: {{ now() }}
Current time: {{ now() }}
{{ $data }}
Current time: {{ now() }}
{{ $stats }}
```
--------------------------------
### Display Validation Errors in View
Source: https://context7.com/livewire/docs/llms.txt
Use the @error directive to display validation messages for specific fields.
```html
```
--------------------------------
### Access Computed Properties in View
Source: https://context7.com/livewire/docs/llms.txt
Computed properties are accessed via the $this object in the view.
```html
{{ $this->post->title }}
{{ $this->post->content }}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.