### Install Livewire via Composer Source: https://laravel-livewire.com/docs/2.x/quickstart Installs the Livewire package into your Laravel project using Composer. This is the first step to start using Livewire. ```shell composer require livewire/livewire ``` -------------------------------- ### Install Livewire via Composer Source: https://laravel-livewire.com/docs/2.x/index Installs the Livewire package into your Laravel project using Composer. This is the first step to start using Livewire. ```shell composer require livewire/livewire ``` -------------------------------- ### Livewire Component Example Source: https://laravel-livewire.com/docs/2.x/lifecycle-hooks A PHP example demonstrating the implementation of various Livewire lifecycle hooks within a component class. ```php class HelloWorld extends Component { public $foo; public function boot() { // } public function booted() { // } public function mount() { // } public function hydrateFoo($value) { // } public function dehydrateFoo($value) { // } public function hydrate() { // } public function dehydrate() { // } public function updating($name, $value) { // } public function updated($name, $value) { // } public function updatingFoo($value) { // } public function updatedFoo($value) { // } public function updatingFooBar($value) { // } public function updatedFooBar($value) { // } } ``` -------------------------------- ### Install AlpineJS for Livewire Source: https://laravel-livewire.com/docs/2.x/alpine-js Explains how to install AlpineJS by adding a script tag to your layout file's head section. It emphasizes the importance of the 'defer' attribute to ensure Alpine waits for Livewire to load first. ```html ... ``` -------------------------------- ### Livewire Dusk Browser Test Example Source: https://laravel-livewire.com/docs/2.x/contribution-guide An example of a Livewire Dusk browser test, demonstrating how to interact with components, perform actions like clicking, and assert visible output. This test type is preferred for ensuring JavaScript and browser interactions work as expected. ```php /** @test */ publicfunction it_can_run_foo_action { $this->browse(function($browser){ Livewire::visit($browser,FooComponent::class) /** * Basic action (click). */ ->waitForLivewire()->click('@foo') ->assertSeeIn('@output','foo') ; }); } ``` -------------------------------- ### Livewire Component Lifecycle Hooks Example Source: https://laravel-livewire.com/docs/2.x/reference Demonstrates the basic structure of a Livewire component class, highlighting the placement of lifecycle hooks like `mount()`. ```php class ShowPost extends Component { public function mount() { // } } ``` -------------------------------- ### Install NPM Dependencies Source: https://laravel-livewire.com/docs/2.x/contribution-guide This command installs all the necessary Node.js and JavaScript dependencies for the Livewire project using npm. It reads the package.json file to download and manage required frontend packages. ```shell npm install ``` -------------------------------- ### Livewire Component Class Methods Example Source: https://laravel-livewire.com/docs/2.x/reference Demonstrates the basic structure of a Livewire component class in PHP, including a `save` method that emits an event. ```PHP class PostForm extends Component { public function save() { ... $this->emit('post-saved'); } } ``` -------------------------------- ### Livewire PHP Testing Methods Example Source: https://laravel-livewire.com/docs/2.x/reference Illustrates how to use Livewire's PHP testing helpers to interact with and assert the behavior of Livewire components during tests. ```PHP public function test() { Livewire::test(ShowPost::class) ->assertDontSee('bar') ->set('foo','bar') ->assertSee('bar'); } ``` -------------------------------- ### Livewire Component Traits Example Source: https://laravel-livewire.com/docs/2.x/reference Shows how to use traits like `WithPagination` to incorporate additional features into a Livewire component. ```php class ShowPost extends Component { use WithPagination; } ``` -------------------------------- ### Install Livewire Package with Composer Source: https://laravel-livewire.com/docs/2.x/installation Installs the Livewire package into your Laravel project using Composer. This is the primary method for adding Livewire to your application. ```Bash composer require livewire/livewire ``` -------------------------------- ### Install Composer Dependencies Source: https://laravel-livewire.com/docs/2.x/contribution-guide This command installs all the necessary PHP dependencies for the Livewire project using Composer. It reads the composer.json file to download and manage required packages. ```shell composer install ``` -------------------------------- ### Livewire: Example Blade View Structure (Blade) Source: https://laravel-livewire.com/docs/2.x/rendering-components An example of a Blade view structure that can be returned from a Livewire component's `render` method. This view iterates over a collection of posts and includes partial views for each post. ```Blade
@foreach ($posts as $post) @include('includes.post', $post) @endforeach
``` -------------------------------- ### Simplify Livewire Mount Method for Query String Source: https://laravel-livewire.com/docs/2.x/upgrading In Livewire v2, component properties are automatically initialized from the query string on page load. This eliminates the need for manual initialization within the `mount()` method, simplifying component setup. ```PHP class Search extends Component { // ... public function mount() { // No need for code like this anymore. // The search property will now be automatically set. // $this->search = request()->query('search', ''); } } ``` -------------------------------- ### Livewire Component Redirect Example Source: https://laravel-livewire.com/docs/2.x/redirecting Demonstrates how to perform a redirect from a Livewire component's action. It shows how to create a new contact and then redirect the user to a success page using Laravel's `redirect()->to()` method. ```php class ContactForm extends Component { public $email; public function addContact() { Contact::create(['email'=>$this->email]); return redirect()->to('/contact-form-success'); } } ``` -------------------------------- ### Initialize Livewire Component Properties with mount Source: https://laravel-livewire.com/docs/2.x/properties Demonstrates how to initialize public properties within a Livewire component using the mount method. This method is called when the component is first mounted, allowing for initial state setup. ```php class HelloWorld extends Component { public $message; public function mount() { $this->message = 'Hello World!'; } } ``` -------------------------------- ### Testing File Downloads with Livewire Source: https://laravel-livewire.com/docs/2.x/file-downloads Example of testing a Livewire component to verify that a file download was triggered correctly. The `assertFileDownloaded` method checks for the presence of the downloaded file. ```PHP /** @test */ public function can_download_export() { Livewire::test(ExportButton::class) ->call('download') ->assertFileDownloaded('export'); } ``` -------------------------------- ### Include Alpine.js v2.7.0 or Greater Source: https://laravel-livewire.com/docs/2.x/upgrading Example of how to correctly include the Alpine.js library in your HTML to ensure compatibility with Livewire V2. It specifies using version 2.7.0 or a later patch release. ```html ``` -------------------------------- ### Laravel Event Broadcasting Example Source: https://laravel-livewire.com/docs/2.x/laravel-echo Demonstrates how to define a Laravel event that implements `ShouldBroadcast` and how to dispatch it using the `event()` helper. This event is intended to be broadcast over WebSockets. ```PHP class OrderShipped implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; public function broadcastOn() { return new Channel('orders'); } } // Dispatching the event: event(new OrderShipped); ``` -------------------------------- ### Livewire Component View Example Source: https://laravel-livewire.com/docs/2.x/redirecting Provides the basic HTML structure for a Livewire component. It includes an input field bound to the component's `$email` property using `wire:model` and a button that triggers the `addContact` action using `wire:click`. ```html
Email:
``` -------------------------------- ### Recompile JavaScript Assets Source: https://laravel-livewire.com/docs/2.x/contribution-guide Commands to manage JavaScript assets for Livewire. 'npm run build' compiles assets for production, while 'npm run watch' starts a watcher to automatically recompile assets during development. ```shell npm run build ``` ```shell npm run watch ``` -------------------------------- ### Livewire Component with Default Pagination Source: https://laravel-livewire.com/docs/2.x/pagination Demonstrates a basic Livewire component utilizing the WithPagination trait for standard pagination. This setup is suitable when only one paginator is present on the page. ```php class ShowPosts extends Livewire\Component { use WithPagination; public function render() { return view('livewire.show-posts', ['posts' => Post::paginate(10)] ); } } ``` -------------------------------- ### Livewire File Storage Options (PHP) Source: https://laravel-livewire.com/docs/2.x/file-uploads Provides examples of different ways to store uploaded files using Livewire, leveraging Laravel's filesystem API. This includes specifying directories, storage disks (like S3), custom filenames, and visibility. ```php // Store the uploaded file in the "photos" directory of the default filesystem disk. $this->photo->store('photos'); // Store in the "photos" directory in a configured "s3" bucket. $this->photo->store('photos','s3'); // Store in the "photos" directory with the filename "avatar.png". $this->photo->storeAs('photos','avatar'); // Store in the "photos" directory in a configured "s3" bucket with the filename "avatar.png". $this->photo->storeAs('photos','avatar','s3'); // Store in the "photos" directory, with "public" visibility in a configured "s3" bucket. $this->photo->storePublicly('photos','s3'); // Store in the "photos" directory, with the name "avatar.png", with "public" visibility in a configured "s3" bucket. $this->photo->storePubliclyAs('photos','avatar','s3'); ``` -------------------------------- ### Livewire: Event Directives (HTML) Source: https://laravel-livewire.com/docs/2.x/actions Illustrates how to use Livewire's event directives to listen for browser events and bind them to component actions. Common directives like wire:click, wire:keydown, and wire:submit are shown with examples. ```HTML ``` ```HTML ``` ```HTML
...
``` ```HTML ``` -------------------------------- ### Registering Custom Livewire Components in PHP Source: https://laravel-livewire.com/docs/2.x/package-dev Demonstrates how to manually register custom Livewire components using the `Livewire::component` method within a service provider's boot method. This is useful for distributing components via Composer packages. The example shows the PHP code for registration and how to use the component in a Blade view. ```PHP class YourPackageServiceProvider extends ServiceProvider { public function boot() { Livewire::component('some-component', SomeComponent::class); } } ``` ```HTML
@livewire('some-component')
``` -------------------------------- ### Testing Livewire File Uploads Source: https://laravel-livewire.com/docs/2.x/file-uploads Provides an example of how to test file upload functionality in a Livewire component using Laravel's testing utilities. It demonstrates creating a fake file, dispatching the upload action, and asserting that the file was stored correctly. ```php /** @test */ public function can_upload_photo() { Storage::fake('avatars'); $file = UploadedFile::fake()->image('avatar.png'); Livewire::test(UploadPhoto::class) ->set('photo', $file) ->call('upload', 'uploaded-avatar.png'); Storage::disk('avatars')->assertExists('uploaded-avatar.png'); } ``` ```php class UploadPhoto extends Component { use WithFileUploads; public $photo; // ... public function upload($name) { $this->photo->storeAs('/', $name, $disk = 'avatars'); } } ``` -------------------------------- ### Test Livewire Component with Passed Data Source: https://laravel-livewire.com/docs/2.x/testing Demonstrates testing a Livewire component by passing initial data directly during the test setup. The `Livewire::test` method accepts an array of data as its second argument, allowing you to pre-populate component properties and assert their initial state. ```PHP use Tests\TestCase; use Livewire\Livewire; use App\Http\Livewire\ShowFoo; class CreatePostTest extends TestCase { /** @test */ function has_data_passed_correctly() { Livewire::test(ShowFoo::class,['foo'=>'bar']) ->assertSet('foo','bar') ->assertSee('bar'); } } ``` ```HTML ``` -------------------------------- ### Create Inline Livewire Component with --inline Flag (PHP) Source: https://laravel-livewire.com/docs/2.x/making-components Demonstrates how to generate an inline Livewire component using the Artisan command. This method creates a component without a dedicated Blade view file, simplifying the setup for basic components. ```bash php artisan make:livewire ShowPosts --inline ``` -------------------------------- ### Livewire 2.x Core Concepts Source: https://laravel-livewire.com/docs/2.x/nesting-components This section covers the fundamental building blocks of Livewire 2.x, including component creation, rendering, properties, and actions. It's essential for understanding how to build dynamic interfaces with PHP. ```APIDOC Livewire Component Basics: - Making Components: Create new Livewire components using Artisan commands. - Rendering Components: How to render components in Blade views using the `` tag. - Properties: Define public properties in your component class to manage state. These properties are automatically synchronized between the server and client. - Actions: Define public methods in your component class that can be called from the frontend via `wire:click`, `wire:submit`, etc. These methods handle user interactions and update component state. ``` -------------------------------- ### Livewire Component Protected Properties Example Source: https://laravel-livewire.com/docs/2.x/reference Illustrates how to define protected properties within a Livewire component class, such as `$rules` for validation. ```php class ShowPost extends Component { protected $rules = ['foo' => 'required|min:6']; } ``` -------------------------------- ### Livewire Component with wire:init Source: https://laravel-livewire.com/docs/2.x/defer-loading This PHP class demonstrates how to implement defer loading using the `wire:init` directive. It includes a property to track readiness and a method that is called on initialization to load data, preventing delays in the initial page render. ```PHP class ShowPost extends Component { public $readyToLoad = false; public function loadPosts() { $this->readyToLoad = true; } public function render() { return view('livewire.show-posts', [ 'posts' => $this->readyToLoad ? Post::all() : [], ] ); } } ``` -------------------------------- ### Initialize Livewire Properties with $this->fill() Source: https://laravel-livewire.com/docs/2.x/properties Shows how to use the $this->fill() method within a Livewire component's mount method to initialize multiple properties concisely. This is useful for reducing visual noise when setting many initial values. ```php public function mount() { $this->fill(['message'=>'Hello World!']); } ``` -------------------------------- ### Livewire 2.x UI Niceties Source: https://laravel-livewire.com/docs/2.x/nesting-components This section covers features that enhance the user interface and experience in Livewire 2.x, such as managing loading states, polling data, prefetching content, handling offline states, tracking dirty states, and deferring component loading. ```APIDOC Livewire UI Enhancements: - Loading States: Display loading indicators while component actions are being processed on the server. - Polling: Automatically re-fetch component data at regular intervals using `wire:poll`. - Prefetching: Load component data proactively when a user hovers over a link or element. - Offline State: Manage component behavior and display messages when the user is offline. - Dirty States: Track changes to component properties and indicate unsaved modifications. - Defer Loading: Delay the initial loading of a component until it's needed or visible. ``` -------------------------------- ### Livewire 2.x Artisan Commands Source: https://laravel-livewire.com/docs/2.x/nesting-components This section lists and describes the Artisan commands available in Livewire 2.x for common development tasks, such as creating components and managing application aspects. ```APIDOC Livewire Artisan Commands: - `php artisan make:livewire component-name`: Generates a new Livewire component, including its class and Blade view. - Other commands may exist for specific tasks like clearing caches or managing assets. ``` -------------------------------- ### Publish Livewire Frontend Assets with Artisan Source: https://laravel-livewire.com/docs/2.x/installation Publishes Livewire's frontend assets (JavaScript and CSS) to your public directory. This is useful if you prefer to serve these assets directly from your web server. ```Bash php artisan livewire:publish --assets ``` -------------------------------- ### Testing Livewire Validation - Specific Rules Source: https://laravel-livewire.com/docs/2.x/input-validation Demonstrates how to test against specific validation rules using Livewire's testing utilities. This example asserts that both 'name' and 'email' fields are required. ```php /** @test */ public function name_and_email_fields_are_required_for_saving_a_contact() { Livewire::test('contact-form') ->set('name','') ->set('email','') ->assertHasErrors([ 'name'=>'required', 'email'=>'required', ]); } ``` -------------------------------- ### Configure Temporary Upload Directory for Livewire (PHP) Source: https://laravel-livewire.com/docs/2.x/file-uploads Specify the directory within the configured disk where temporary files are stored during uploads. The default is `livewire-tmp/`. This example sets the directory to `tmp`. ```PHP return[ 'temporary_file_upload'=>[ 'directory'=>'tmp', ], ]; ``` -------------------------------- ### Livewire: Root Element Issue Example Source: https://laravel-livewire.com/docs/2.x/troubleshooting Demonstrates a common Livewire error where a component has multiple root elements. This prevents child elements, like buttons with `wire:click`, from functioning correctly. ```blade
Some content
``` -------------------------------- ### Livewire: Basic Action Usage (PHP & HTML) Source: https://laravel-livewire.com/docs/2.x/actions Demonstrates the fundamental concept of actions in Livewire, where UI interactions trigger methods on a Livewire component. It shows a PHP component with a 'like' method and the corresponding HTML button to invoke it. ```PHP class ShowPost extends Component { public Post $post; public function like() { $this->post->addLikeBy(auth()->user()); } } ``` ```HTML
``` -------------------------------- ### Clone Livewire Repository Locally Source: https://laravel-livewire.com/docs/2.x/contribution-guide This command clones your forked Livewire repository from GitHub to your local machine. It specifies the Git repository URL and the local directory where the project will be cloned. ```shell git clone git@github.com:username/livewire.git~/packages/livewire ``` -------------------------------- ### Direct Laravel Response Download Source: https://laravel-livewire.com/docs/2.x/file-downloads Illustrates using Laravel's `response()->download()` directly within a component or controller. This provides more control over the download process. ```PHP return response()->download(storage_path('exports/export.csv')); ``` -------------------------------- ### Show Loading Indicator with wire:loading Source: https://laravel-livewire.com/docs/2.x/loading-states This example demonstrates how to show a loading message while a Livewire action is processing. The `wire:loading` directive makes the enclosed element visible only during network requests triggered by Livewire. ```blade
Processing Payment...
``` -------------------------------- ### Testing Livewire Validation - Basic Assertions Source: https://laravel-livewire.com/docs/2.x/input-validation Provides examples of using Livewire's testing utilities to assert validation states. This snippet tests if specific fields are marked as having errors after setting them to empty values. ```php /** @test */ public function name_and_email_fields_are_required_for_saving_a_contact() { Livewire::test('contact-form') ->set('name','') ->set('email','') ->assertHasErrors(['name','email']); } ``` -------------------------------- ### Publish Livewire Configuration File with Artisan Source: https://laravel-livewire.com/docs/2.x/installation Publishes Livewire's configuration file to your application's config directory. This allows for customization of Livewire's behavior and settings. ```Bash php artisan livewire:publish --config ``` -------------------------------- ### Livewire Keydown Modifiers Source: https://laravel-livewire.com/docs/2.x/actions Listen for specific key presses on keydown events using Livewire modifiers. Convert native KeyboardEvent.key values to kebab-case. Examples include 'backspace', 'escape', 'shift', 'tab', and 'arrow-right'. ```html ``` -------------------------------- ### Livewire $wire Object API Source: https://laravel-livewire.com/docs/2.x/reference The $wire object provides an interface for Alpine.js components to interact with Livewire components. It allows for getting and setting component properties, calling component methods, and listening for or emitting events. ```APIDOC $wire.foo Get the value of the "foo" property on the Livewire component. $wire.foo = 'bar' Set the value of the "foo" property on the Livewire component. $wire.bar(..args) Call the "bar" method (with params) on the Livewire component. let baz = await $wire.bar(..args) Call the "bar" method, wait for the response, and set `baz` to it. $wire.on('foo', (..args) => { ... }) Call a function when the "foo" event is emitted from the Livewire component. $wire.emit('foo', ...args) Emit the "foo" event to all Livewire components. $wire.emitUp('foo', ...args) Emit the "foo" event to parent components. $wire.emitSelf('foo', ...args) Emit the "foo" event only to this component. $wire.get('foo') Get the "foo" property from the Livewire component. $wire.set('foo', 'bar') Set the "foo" property on the component. $wire.set('foo', 'bar', true) Defer setting the "foo" property on the component until the next request. $wire.call('foo', ..args) Call the "foo" method with params on the component. x-data="{ foo: $wire.entangle('foo') }" Entangle the value of "foo" between Livewire and Alpine.js, creating a two-way binding. $wire.entangle('foo').defer Configure entangle to only update the Livewire property on the next fired Livewire request. ``` -------------------------------- ### Debouncing Livewire Input with wire:model.debounce Source: https://laravel-livewire.com/docs/2.x/properties Shows how to apply a debounce modifier to the wire:model directive to limit the frequency of network requests sent as a user types. The example uses a 500ms debounce for text inputs. ```html ``` -------------------------------- ### Navigate to Livewire Directory Source: https://laravel-livewire.com/docs/2.x/contribution-guide After cloning the repository, this command changes your current working directory to the newly cloned Livewire project folder, allowing you to execute subsequent commands within the project context. ```shell cd ~/packages/livewire ``` -------------------------------- ### Reusable Blade Component with Alpine.js Source: https://laravel-livewire.com/docs/2.x/alpine-js Demonstrates extracting Alpine.js logic into a reusable Blade component for use within Livewire. This example shows a Livewire view that utilizes a custom dropdown component, separating concerns and promoting reusability. ```blade
``` ```blade
{{$trigger }}
{{$slot }}
``` -------------------------------- ### Update Dusk Browser Drivers Source: https://laravel-livewire.com/docs/2.x/contribution-guide This command utilizes the bundled Dusk updater to detect and automatically update the necessary browser drivers (like ChromeDriver) required for running browser-based tests with Laravel Dusk. Ensure Chrome is installed. ```shell ./vendor/bin/dusk-updater detect --auto-update ``` -------------------------------- ### Livewire: PHP Array Structure for Checksum Source: https://laravel-livewire.com/docs/2.x/troubleshooting Provides an example of a PHP component property containing an array. It highlights the importance of array key order (numeric before alphanumeric) to prevent checksum validation errors caused by JavaScript object conversion. ```php class HelloWorld extends Component { public $list = [ '123' => 456, 'foo' => 'bar' ]; ... } ``` -------------------------------- ### Livewire 2.x Component Features Source: https://laravel-livewire.com/docs/2.x/nesting-components This section details advanced features for managing component behavior and user experience in Livewire 2.x, including validation, file handling, query string integration, authorization, pagination, and redirecting. ```APIDOC Livewire Component Advanced Features: - Validation: Implement server-side validation for component inputs using Livewire's built-in validation rules or custom logic. - File Uploads: Handle file uploads directly within Livewire components, including progress tracking and storage. - File Downloads: Implement functionality to trigger file downloads from within Livewire components. - Query String: Synchronize component state with the browser's URL query string to allow for bookmarkable and shareable states. - Authorization: Integrate authorization logic to control access to component actions and data based on user permissions. - Pagination: Implement server-driven pagination for lists and tables within Livewire components. - Redirecting: Perform redirects to different pages or routes from within component actions. ``` -------------------------------- ### Toggle HTML Attributes with Livewire Loading States Source: https://laravel-livewire.com/docs/2.x/loading-states This example shows how to use the `wire:loading.attr` directive in Livewire to toggle HTML attributes on an element while a component is loading. It's useful for disabling buttons or showing/hiding elements during asynchronous operations. ```HTML ``` -------------------------------- ### Configure Middleware for Livewire File Upload Endpoint (PHP) Source: https://laravel-livewire.com/docs/2.x/file-uploads Customize the middleware applied to the temporary file upload endpoint. By default, Livewire uses throttling. This example demonstrates how to limit uploads to 5 per user per minute. ```PHP return[ 'temporary_file_upload'=>[ 'middleware'=>'throttle:5,1', // Only allow 5 uploads per user per minute. ], ]; ``` -------------------------------- ### Configure Global Validation Rules for Livewire File Uploads (PHP) Source: https://laravel-livewire.com/docs/2.x/file-uploads Customize the default validation rules applied to all temporary file uploads in Livewire. The default is `file|max:12288`. This example shows how to set custom rules for file type and size. ```PHP return[ 'temporary_file_upload'=>[ 'rules'=>'file|mimes:png,jpg,pdf|max:102400', // (100MB max, and only pngs, jpegs, and pdfs.) ], ]; ``` -------------------------------- ### Configure Maximum Upload Time for Livewire File Uploads (PHP) Source: https://laravel-livewire.com/docs/2.x/file-uploads Set the maximum time in minutes allowed for a file upload to complete before it is invalidated. The default is 5 minutes. This example sets the maximum upload time to 5 minutes. ```PHP return[ 'temporary_file_upload'=>[ 'max_upload_time'=>5, ], ]; ``` -------------------------------- ### HTML for Eloquent Relationship Binding Source: https://laravel-livewire.com/docs/2.x/properties Demonstrates the HTML for binding to properties of related models within a loop. It uses `wire:model` with index notation for the relationship (e.g., `user.posts.{{ $i }}.title`) and includes an example of displaying validation errors using `@error`. ```HTML
@foreach ($user->posts as $i => $post) @error('user.posts.{{$i}}.title') {{ $message }} @enderror @endforeach
``` -------------------------------- ### Basic Livewire Component Rendering Test Source: https://laravel-livewire.com/docs/2.x/testing A fundamental test to verify that a Livewire component can be rendered successfully. It instantiates the component using `Livewire::test` and then asserts that the HTTP response status is 200 OK, indicating successful rendering. ```PHP use Tests\TestCase; use Livewire\Livewire; use App\Http\Livewire\ShowPosts; class ShowPostsTest extends TestCase { /** @test */ public function the_component_can_render() { $component = Livewire::test(ShowPosts::class); $component->assertStatus(200); } } ``` -------------------------------- ### Generate Livewire Component Test File Source: https://laravel-livewire.com/docs/2.x/testing Creates a new Livewire component along with a corresponding PHPUnit test file. This is achieved by using the `make:livewire` Artisan command with the `--test` flag, streamlining the development workflow by providing a boilerplate test structure. ```Shell php artisan make:livewire ShowPosts --test ``` -------------------------------- ### Livewire Pagination Component with wire:click (Blade/PHP) Source: https://laravel-livewire.com/docs/2.x/pagination An example of a custom Livewire pagination component that uses `wire:click` directives for navigation. This approach replaces traditional anchor tags with Livewire actions, enabling seamless client-side pagination updates. ```blade
@if($paginator->hasPages()) @endif
``` -------------------------------- ### Livewire: Action Parameter Handling (PHP) Source: https://laravel-livewire.com/docs/2.x/actions Details how parameters passed from the HTML view are received by the Livewire component's methods. It demonstrates standard PHP parameter binding and how to resolve models directly using type hints. ```PHP public function addTodo($id, $name) { // ... } ``` ```PHP public function addTodo(Todo $todo, $name) { // ... } ``` -------------------------------- ### Blade Template with wire:init Source: https://laravel-livewire.com/docs/2.x/defer-loading This Blade template shows how to attach the `wire:init` directive to a Livewire component's root element. This directive triggers the specified method (e.g., `loadPosts`) as soon as the component is rendered on the page, allowing for asynchronous data loading. ```Blade
    @foreach ($posts as $post)
  • {{ $post->title }}
  • @endforeach
``` -------------------------------- ### Default Livewire JavaScript Script Tag Source: https://laravel-livewire.com/docs/2.x/installation By default, Livewire generates a script tag to load its JavaScript from the `/livewire/livewire.js` route. This default behavior can fail if your application is hosted on a sub-path or if assets are served from a different base URL, as shown in the configuration examples. ```html ``` -------------------------------- ### Component Action for File Download Source: https://laravel-livewire.com/docs/2.x/file-downloads Demonstrates how to return a Laravel file download from a Livewire component action. This method is straightforward for basic file serving. ```PHP class ExportButton extends Component { public function export() { return Storage::disk('exports')->download('export.csv'); } } ``` -------------------------------- ### Toggling Classes on Referenced Elements Source: https://laravel-livewire.com/docs/2.x/dirty-states This example demonstrates how to apply a CSS class ('text-red-500') to a label element when the associated input element's value becomes dirty. It utilizes Livewire's `wire:dirty.class` directive targeting the 'foo' property. ```html
``` -------------------------------- ### Livewire: Route Model Binding in Mount (PHP) Source: https://laravel-livewire.com/docs/2.x/rendering-components Shows how Livewire components support route model binding directly in the `mount` method. By type-hinting a model, Livewire automatically resolves and injects the corresponding Eloquent model instance. ```PHP use App\Http\Livewire\ShowPost; use App\Models\Post; use Illuminate\Support\Facades\Route; Route::get('/post/{post}', ShowPost::class); class ShowPost extends Component { public $post; public function mount(Post $post) { $this->post = $post; } } ``` -------------------------------- ### Livewire Component Test: CreatePostTest Source: https://laravel-livewire.com/docs/2.x/testing This PHP code demonstrates how to test the `CreatePost` Livewire component using Livewire's testing utilities. It includes tests for creating a post, setting initial data, validating required fields, and asserting redirects after successful creation. ```PHP class CreatePostTest extends TestCase { /** @test */ function can_create_post() { $this->actingAs(User::factory()->create()); Livewire::test(CreatePost::class) ->set('title', 'foo') ->call('create'); $this->assertTrue(Post::whereTitle('foo')->exists()); } /** @test */ function can_set_initial_title() { $this->actingAs(User::factory()->create()); Livewire::test(CreatePost::class, ['initialTitle' => 'foo']) ->assertSet('title', 'foo'); } /** @test */ function title_is_required() { $this->actingAs(User::factory()->create()); Livewire::test(CreatePost::class) ->set('title', '') ->call('create') ->assertHasErrors(['title' => 'required']); } /** @test */ function is_redirected_to_posts_page_after_creation() { $this->actingAs(User::factory()->create()); Livewire::test(CreatePost::class) ->set('title', 'foo') ->call('create') ->assertRedirect('/posts'); } } ``` -------------------------------- ### Create Livewire Component in Sub-folder Source: https://laravel-livewire.com/docs/2.x/making-components Allows for the creation of Livewire components within sub-directories, organizing components logically. This supports different syntaxes for specifying the sub-folder path. ```php php artisan make:livewire Post\Show ``` ```php php artisan make:livewire Post/Show ``` ```php php artisan make:livewire post.show ``` -------------------------------- ### HTML for Single Eloquent Model Binding Source: https://laravel-livewire.com/docs/2.x/properties Shows the HTML form structure for binding to Eloquent model properties using `wire:model`. This example binds to `post.title` and `post.content`, enabling two-way data flow between the form inputs and the component's model property. ```HTML
``` -------------------------------- ### Livewire 2.x JavaScript Integrations Source: https://laravel-livewire.com/docs/2.x/nesting-components This section explains how to integrate Livewire 2.x with popular JavaScript libraries and patterns, specifically Alpine.js and Laravel Echo, and how to manage inline scripts within components. ```APIDOC Livewire JS Integrations: - AlpineJS: Seamlessly integrate Alpine.js directives and behavior with Livewire components for enhanced frontend interactivity. - Laravel Echo: Connect Livewire components to Laravel Echo to receive real-time events from the backend and update the UI accordingly. - Inline Scripts: Safely execute JavaScript directly within your Livewire component views, ensuring proper scoping and lifecycle management. ```