### Setup Livewire Locally
Source: https://livewire.laravel.com/docs/contribution-guide
This snippet demonstrates how to set up the Livewire project locally for contribution. It involves forking the repository, cloning it, installing Composer dependencies, and configuring Dusk.
```Bash
# Fork and clone Livewire
gh repo fork livewire/livewire --default-branch-only --clone=true --remote=false -- livewire
# Switch the working directory to livewire
cd livewire
# Install all composer dependencies
composer install
# Ensure Dusk is correctly configured
vendor/bin/dusk-updater detect --no-interaction
```
--------------------------------
### Setup Alpine.js Locally and Link Packages
Source: https://livewire.laravel.com/docs/contribution-guide
This snippet details the process of setting up Alpine.js locally, including forking, cloning, installing npm dependencies, building packages, and linking them. It concludes by linking Alpine.js packages to the Livewire project and building Livewire.
```Shell
# Fork and clone Alpine
gh repo fork alpinejs/alpine --default-branch-only --clone=true --remote=false -- alpine
# Switch the working directory to alpine
cd alpine
# Install all npm dependencies
npm install
# Build all Alpine packages
npm run build
# Link all Alpine packages locally
cd packages/alpinejs && npm link && cd ../..
cd packages/anchor && npm link && cd ../..
cd packages/collapse && npm link && cd ../..
cd packages/csp && npm link && cd ../..
cd packages/docs && npm link && cd ../..
cd packages/focus && npm link && cd ../..
cd packages/history && npm link && cd ../..
cd packages/intersect && npm link && cd ../..
cd packages/mask && npm link && cd ../..
cd packages/morph && npm link && cd ../..
cd packages/navigate && npm link && cd ../..
cd packages/persist && npm link && cd ../..
cd packages/sort && npm link && cd ../..
cd packages/ui && npm link && cd ../..
# Switch the working directory back to livewire
cd ../livewire
# Link all packages
npm link alpinejs @alpinejs/anchor @alpinejs/collapse @alpinejs/csp @alpinejs/docs @alpinejs/focus @alpinejs/history @alpinejs/intersect @alpinejs/mask @alpinejs/morph @alpinejs/navigate @alpinejs/persist @alpinejs/sort @alpinejs/ui
# Build Livewire
npm run build
```
--------------------------------
### Livewire Test Setup: Instantiate Component
Source: https://livewire.laravel.com/docs/testing
Demonstrates how to instantiate and test a specific Livewire component using `Livewire::test()`. This is the starting point for most component tests.
```PHP
Livewire::test(CreatePost::class)
```
--------------------------------
### Browser Test Example for Livewire
Source: https://livewire.laravel.com/docs/contribution-guide
An example of a basic browser test for Livewire, showing how to set up a test class that extends BrowserTestCase and includes a test method for browser interactions.
```php
use Tests\BrowserTestCase;
class BrowserTest extends BrowserTestCase
{
/** @test */
public function livewire_can_run_action()
{
// ...
}
}
```
--------------------------------
### Install Livewire with Composer
Source: https://livewire.laravel.com/docs/index
This command installs the Livewire package into your Laravel project using Composer. Ensure you have Composer installed and are in your Laravel project's root directory.
```bash
composer require livewire/livewire
```
--------------------------------
### PHP Unit Test Example for Livewire
Source: https://livewire.laravel.com/docs/contribution-guide
An example of a basic PHP unit test for Livewire, demonstrating how to set up a test class that extends TestCase and includes a test method.
```php
use Tests\TestCase;
class UnitTest extends TestCase
{
/** @test */
public function livewire_can_run_action(): void
{
// ...
}
}
```
--------------------------------
### Basic Livewire Navigation Setup (PHP)
Source: https://livewire.laravel.com/docs/navigate
This snippet shows the basic setup in a Laravel routes file to define Livewire components as routes. These routes can then be targeted by `wire:navigate`.
```PHP
use App\Livewire\Dashboard;
use App\Livewire\ShowPosts;
use App\Livewire\ShowUsers;
Route::get('/', Dashboard::class);
Route::get('/posts', ShowPosts::class);
Route::get('/users', ShowUsers::class);
```
--------------------------------
### Livewire Test Setup: Instantiate Component with Mount Parameters
Source: https://livewire.laravel.com/docs/testing
Shows how to test a Livewire component and pass initial parameters to its `mount()` method.
```PHP
Livewire::test(UpdatePost::class, ['post' => $post])
```
--------------------------------
### Install Livewire with Composer
Source: https://livewire.laravel.com/docs/installation
This command installs the Livewire package into your Laravel application using Composer. Ensure you have a Laravel application set up and are in its root directory in your terminal.
```bash
composer require livewire/livewire
```
--------------------------------
### Install Volt Service Provider (Artisan)
Source: https://livewire.laravel.com/docs/volt
After installing the Volt package, this Artisan command registers Volt's service provider. This enables Volt to find and process your single-file components.
```bash
php artisan volt:install
```
--------------------------------
### Define Route for Livewire Page Component (PHP)
Source: https://livewire.laravel.com/docs/upgrading
This example shows how to define a route that renders a Livewire component as a full page, a common pattern in Livewire applications.
```PHP
Route::get('/posts', ShowPosts::class);
```
--------------------------------
### Manually Bundle Livewire and Alpine.js (JavaScript)
Source: https://livewire.laravel.com/docs/installation
This JavaScript snippet illustrates how to import and start Livewire and Alpine.js manually after disabling automatic script injection. It includes an example of registering an Alpine.js plugin.
```JavaScript
// Warning: This snippet demonstrates what NOT to do...
import Alpine from 'alpinejs'
import Clipboard from '@ryangjchandler/alpine-clipboard'
Alpine.plugin(Clipboard)
Alpine.start()
```
```JavaScript
import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm';
import Clipboard from '@ryangjchandler/alpine-clipboard'
Alpine.plugin(Clipboard)
Livewire.start()
```
--------------------------------
### Install Volt Package (Composer)
Source: https://livewire.laravel.com/docs/volt
This command installs the Livewire Volt package into your Laravel project using Composer. It's the first step to integrating Volt's features.
```bash
composer require livewire/volt
```
--------------------------------
### Livewire Specific Child Component Example
Source: https://livewire.laravel.com/docs/nesting
This PHP code defines a basic Livewire component 'StepOne' which is intended to be rendered dynamically. It serves as an example of a child component that can be displayed based on runtime conditions.
```php
@if ($errors->has('title'))
{{ $errors->first('title') }}
@endif
```
--------------------------------
### Livewire Navigation Progress Bar Configuration
Source: https://livewire.laravel.com/docs/navigate
Provides an example of how to configure the progress bar's visibility and color in Livewire's configuration file (`config/livewire.php`).
```php
'navigate' => [
'show_progress_bar' => false,
'progress_bar_color' => '#2299dd',
],
```
--------------------------------
### Livewire Volt: Render Component with Tag Syntax
Source: https://livewire.laravel.com/docs/volt
Example of rendering a Volt component using Livewire's standard tag syntax, including passing properties.
```Blade
```
--------------------------------
### Livewire UpdatePost Component Example
Source: https://livewire.laravel.com/docs/security
An example of a Livewire component that fetches and updates a 'Post' model. It includes validation using Livewire's #[Validate] attribute and demonstrates the mount and update methods.
```php
title = $this->post->title;
$this->content = $this->post->content;
}
public function update()
{
$this->post->update([
'title' => $this->title,
'content' => $this->content,
]);
}
}
```
--------------------------------
### Laravel Route Definition for Full-Page Component
Source: https://livewire.laravel.com/docs/redirecting
Example of configuring a Livewire component to act as a full-page component for a given route.
```PHP
use App\Livewire\ShowPosts;
Route::get('/posts', ShowPosts::class);
```
--------------------------------
### Eloquent Model Binding Example (Livewire 2)
Source: https://livewire.laravel.com/docs/upgrading
This code snippet demonstrates the Eloquent model binding pattern supported in Livewire 2, where `wire:model` could directly bind to model properties.
```PHP
public Post $post;
protected $rules = [
'post.title' => 'required',
'post.description' => 'required',
];
```
```Blade
```
--------------------------------
### Generate Livewire Component
Source: https://livewire.laravel.com/docs/index
This Artisan command generates the necessary PHP and Blade files for a new Livewire component. Replace 'counter' with your desired component name.
```bash
php artisan make:livewire counter
```
--------------------------------
### Manually Navigate to a New URL with Livewire
Source: https://livewire.laravel.com/docs/navigate
Provides an example of how to manually trigger a page visit to a new URL using the Livewire.navigate() JavaScript method.
```javascript
Livewire.navigate('/new/url')
```
--------------------------------
### Livewire Volt: Define Mount Lifecycle Hook
Source: https://livewire.laravel.com/docs/volt
Example of using the `mount` function to define the component's mount lifecycle hook, injecting parameters and resolving dependencies.
```PHP
use App\Services\UserCounter;
use function Livewire\Volt\mount;
mount(function (UserCounter $counter, $users) {
$counter->store('userCount', count($users));
// ...
});
```
--------------------------------
### Create a New Git Branch
Source: https://livewire.laravel.com/docs/contribution-guide
This command demonstrates how to create a new branch in Git for feature development or bug fixes, ensuring changes are isolated.
```bash
git checkout -b my-feature
```
--------------------------------
### Livewire Volt: Define Initial State Property
Source: https://livewire.laravel.com/docs/volt
Example of defining an initial state property with a default value using the `state` function.
```PHP
0]);
?>
{{ $count }}
```
--------------------------------
### Livewire Component Example (PHP)
Source: https://livewire.laravel.com/docs/morphing
A basic Livewire component demonstrating state management and actions. It includes a public property for input and an array to store items, with a method to add new items.
```php
class Todos extends Component
{
public $todo = '';
public $todos = [
'first',
'second',
];
public function add()
{
$this->todos[] = $this->todo;
}
}
```
--------------------------------
### Dispatching and Listening for Events in Livewire 3
Source: https://livewire.laravel.com/docs/upgrading
Demonstrates how to dispatch and listen for events in Livewire 3 using the unified `dispatch` method. This replaces the older `emit` and `dispatchBrowserEvent` methods.
```PHP
class CreatePost extends Component
{
public Post $post;
public function save()
{
$this->dispatch('post-created', postId: $this->post->id);
}
}
class Dashboard extends Component
{
#[On('post-created')]
public function postAdded($postId)
{
//
}
}
```
--------------------------------
### Livewire Test Setup: Set Query Parameters
Source: https://livewire.laravel.com/docs/testing
Configures URL query parameters for the test, simulating how a component might receive data via the URL using Livewire's `#[Url]` attribute.
```PHP
Livewire::withQueryParams(['search' => '...'])
```
--------------------------------
### Livewire Component for Entangled State
Source: https://livewire.laravel.com/docs/alpine
A PHP example of a Livewire component demonstrating state management for dropdown visibility using a public property that can be entangled with Alpine.js.
```php
use Livewire\Component;
class PostDropdown extends Component
{
public $showDropdown = false;
public function archive()
{
// ...
$this->showDropdown = false;
}
public function delete()
{
// ...
$this->showDropdown = false;
}
}
```
--------------------------------
### Livewire Project Structure for Tests
Source: https://livewire.laravel.com/docs/contribution-guide
This snippet shows the directory structure within the Livewire project where tests can be added, categorized by Livewire features.
```text
src/Features/SupportAccessingParent
src/Features/SupportAttributes
src/Features/SupportAutoInjectedAssets
src/Features/SupportBladeAttributes
src/Features/SupportChecksumErrorDebugging
src/Features/SupportComputed
src/Features/SupportConsoleCommands
src/Features/SupportDataBinding
//...
```
--------------------------------
### Dispatch Livewire Events (PHP & JavaScript)
Source: https://livewire.laravel.com/docs/testing
Demonstrates dispatching custom events from a Livewire component, which can be listened to by other Livewire components or JavaScript. Includes examples with and without parameters.
```php
use Livewire\Component;
class MyComponent extends Component
{
public $postId = 1;
public function render()
{
return view('livewire.my-component');
}
public function dispatchPostCreatedEvent()
{
$this->dispatch('post-created');
}
public function dispatchPostCreatedWithIdEvent()
{
$this->dispatch('post-created', postId: $this->postId);
}
}
// In JavaScript (e.g., Alpine.js):
// document.addEventListener('livewire:init', () => {
// Livewire.on('post-created', (event) => {
// console.log('Post created event received:', event.detail);
// });
// });
```
--------------------------------
### Default Livewire Layout Structure
Source: https://livewire.laravel.com/docs/components
This is an example of the default `app.blade.php` layout file generated by Livewire. It includes basic HTML structure and a `{{ $slot }}` placeholder for component content.
```Blade
{{ $title ?? 'Page Title' }}
{{ $slot }}
```
--------------------------------
### PHP Livewire Counter Component
Source: https://livewire.laravel.com/docs/hydration
Example of a basic Livewire component in PHP that increments a counter. It demonstrates the `render` method for returning Blade views and a public method for handling user interactions.
```PHP
class Counter extends Component
{
public $count = 1;
public function increment()
{
$this->count++;
}
public function render()
{
return <<<'HTML'
Count: {{ $count }}
HTML;
}
}
```
--------------------------------
### Livewire 3 New Configuration Options
Source: https://livewire.laravel.com/docs/upgrading
These are new configuration keys introduced in Livewire version 3. They control features like legacy model binding, asset injection, and pagination themes.
```php
'legacy_model_binding' => false,
'inject_assets' => true,
'inject_morph_markers' => true,
'navigate' => false,
'pagination_theme' => 'tailwind',
```
--------------------------------
### Livewire Parent Component (Posts)
Source: https://livewire.laravel.com/docs/understanding-nesting
Example of a parent Livewire component that fetches and displays a list of posts, allowing for dynamic updates to the post limit. It renders nested 'show-post' components for each post.
```PHP
Auth::user()->posts()
->limit($this->postLimit)->get(),
]);
}
}
```
```HTML
Post Limit:
@foreach ($posts as $post)
@endforeach
```
--------------------------------
### Layout with Persisted Audio Player
Source: https://livewire.laravel.com/docs/navigate
An example of a main layout file (`app.blade.php`) that includes a persisted audio player using the @persist directive, ensuring playback continuity during navigation.
```html
{{ $title ?? 'Page Title' }}
{{ $slot }}
@persist('player')
@endpersist
```
--------------------------------
### Remove wire:click.prefetch
Source: https://livewire.laravel.com/docs/upgrading
The `wire:click.prefetch` directive has been removed in Livewire 3. This change affects how Livewire handles click events for performance optimization. The provided example shows the removal of the `.prefetch` modifier.
```html