### Setup Livewire locally Source: https://livewire.laravel.com/docs/4.x/contribution-guide Commands to fork, clone, and install dependencies for the Livewire repository. ```shell # Fork and clone Livewire gh repo fork livewire/livewire --default-branch-only --clone=true -- 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 ``` -------------------------------- ### Basic Livewire Pagination Setup Source: https://livewire.laravel.com/docs/4.x/pagination Demonstrates the fundamental setup for pagination in a Livewire component. It requires the `WithPagination` trait and uses `Post::paginate(10)` to fetch data and `$this->posts->links()` to render navigation. This enables seamless page transitions within the same page view. ```php
@foreach ($this->posts as $post) @endforeach
{{ $this->posts->links() }} ``` -------------------------------- ### Livewire Setup Methods Source: https://livewire.laravel.com/docs/4.x/testing Methods for configuring the testing environment before interacting with Livewire components. ```APIDOC ## Livewire Setup Methods ### Description Methods for configuring the testing environment before interacting with Livewire components. ### Methods #### `Livewire::test('component.name')` **Description:** Test the specified Livewire component. **Example:** `Livewire::test('post.create')` #### `Livewire::test(ComponentClass::class, ['param' => $value])` **Description:** Test a Livewire component class, passing parameters to its `mount()` method. **Example:** `Livewire::test(UpdatePost::class, ['post' => $post])` #### `Livewire::actingAs($user)` **Description:** Set the authenticated user for the current test. **Example:** `Livewire::actingAs($user)` #### `Livewire::withQueryParams(['param' => 'value'])` **Description:** Set URL query parameters for the test. **Example:** `Livewire::withQueryParams(['search' => 'livewire'])` #### `Livewire::withCookie('name', 'value')` **Description:** Set a single cookie for the test. **Example:** `Livewire::withCookie('session', '...')` #### `Livewire::withCookies(['name1' => 'value1', 'name2' => 'value2'])` **Description:** Set multiple cookies for the test. **Example:** `Livewire::withCookies(['color' => 'blue', 'user' => 'test'])` #### `Livewire::withHeaders(['X-Header' => 'value'])` **Description:** Set custom HTTP headers for the test. **Example:** `Livewire::withHeaders(['Authorization' => 'Bearer ...'])` #### `Livewire::withoutLazyLoading()` **Description:** Disable lazy loading for all components within this test. **Example:** `Livewire::withoutLazyLoading()` ``` -------------------------------- ### Setup Alpine locally Source: https://livewire.laravel.com/docs/4.x/contribution-guide Commands to fork, clone, build, and link Alpine packages for local development. ```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 ``` -------------------------------- ### Example of a Dynamically Rendered Livewire Step Component Source: https://livewire.laravel.com/docs/4.x/nesting This is an example of a simple Livewire component that could be dynamically rendered by a parent component. It displays basic content and serves as a placeholder for a specific step in a process. This component requires no specific props or methods for this basic example. ```php
Step One Content
``` -------------------------------- ### Use Simple and Cursor Pagination Source: https://livewire.laravel.com/docs/4.x/pagination Examples of using simplePaginate for basic navigation and cursorPaginate for high-performance pagination on large datasets. ```php public function render() { return view('show-posts', [ 'posts' => Post::simplePaginate(10), ]); } public function renderCursor() { return view('show-posts', [ 'posts' => Post::cursorPaginate(10), ]); } ``` -------------------------------- ### Basic wire:click Syntax Source: https://livewire.laravel.com/docs/4.x/wire-click Reference examples for the basic syntax of the `wire:click` directive. ```html wire:click="methodName" wire:click="methodName(param1, param2)" ``` -------------------------------- ### Install Livewire via Composer Source: https://livewire.laravel.com/docs/4.x/installation Run this command in your Laravel application root to install the Livewire package. ```shell composer require livewire/livewire ``` -------------------------------- ### Example: Real-time Notification Bell Source: https://livewire.laravel.com/docs/4.x/attribute-on A practical example showcasing how #[On] can be used to implement a real-time notification counter. ```APIDOC ## POST /notification/update ### Description This example demonstrates a notification bell component that updates its unread count based on dispatched events. ### Method POST (simulated event dispatch) ### Endpoint N/A (Client-side event listening and dispatching) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php unreadCount = auth()->user()->unreadNotifications()->count(); } #[On('notification-sent')] // Listen for new notifications public function incrementCount() { $this->unreadCount++; } #[On('notifications-read')] // Listen for notifications being marked as read public function resetCount() { $this->unreadCount = 0; } }; ?> ``` ```php // Dispatching events from other parts of the application // Example: Dispatching when a new notification is sent $this->dispatch('notification-sent'); // Example: Dispatching when notifications are read $this->dispatch('notifications-read'); ``` ### Response #### Success Response (200) None (Component state updates) #### Response Example (No direct response, UI updates dynamically based on event triggers) ``` -------------------------------- ### Install Pest Browser Testing Plugin Source: https://livewire.laravel.com/docs/4.x/testing Commands to install the Pest browser testing plugin and Playwright, enabling browser automation for testing Livewire components. ```shell composer require pestphp/pest-plugin-browser --dev npm install playwright@latest npx playwright install ``` -------------------------------- ### Start Laravel Development Server (Shell) Source: https://livewire.laravel.com/docs/4.x/quickstart This command starts the built-in PHP development server for a Laravel application, making it accessible via a local URL. It's a common step for testing Laravel applications during development. Requires PHP and Composer installed. ```shell php artisan serve ``` -------------------------------- ### Test Livewire with PHPUnit Source: https://livewire.laravel.com/docs/4.x/testing Provides an example of using standard PHPUnit syntax to test Livewire components as an alternative to Pest. ```php assertEquals(0, Post::count()); Livewire::test('post.create') ->set('title', 'My new post') ->set('content', 'Post content') ->call('save'); $this->assertEquals(1, Post::count()); } } ``` -------------------------------- ### Install Pest for Livewire Testing Source: https://livewire.laravel.com/docs/4.x/testing Commands to remove PHPUnit and install Pest as the testing framework for Livewire components. Pest is recommended for its simplicity and integration with Livewire. ```shell composer remove phpunit/phpunit composer require pestphp/pest --dev --with-all-dependencies ./vendor/bin/pest --init ``` -------------------------------- ### Dynamic Child Component Rendering Source: https://livewire.laravel.com/docs/4.x/nesting This example shows how to render child components dynamically at run-time using the `` tag and an `:is` prop. ```APIDOC ## Dynamic child components ### Description This example demonstrates how to render child components dynamically at run-time using the `` tag, which accepts an `:is` prop to specify the component to render. ### Method N/A (Component rendering) ### Endpoint N/A (Component rendering) ### Parameters #### Query Parameters - **is** (string) - Required - The name of the component to render. ### Request Example ```html ``` ### Response N/A (Component rendering) ``` ```APIDOC ## Dynamic Child Component Example (Multi-step Form) ### Description This example illustrates a practical use case for dynamic components: rendering different steps of a multi-step form. ### Method N/A (Component rendering) ### Endpoint N/A (Component rendering) ### Parameters #### Path Parameters - **current** (string) - Required - The name of the current step component to display. #### Query Parameters - **wire:key** (string) - Required - A unique key to ensure proper re-rendering of the dynamic component. ### Request Example ```php current, $this->steps); $this->current = $this->steps[$currentIndex + 1]; } }; ?>
``` ### Response N/A (Component rendering) ``` ```APIDOC ## Example of a Dynamic Child Component ### Description This shows a simple child component that would be rendered by the dynamic component example above. ### Method N/A (Component definition) ### Endpoint N/A (Component definition) ### Parameters N/A ### Request Example ```php
Step One Content
``` ### Response N/A (Component definition) ``` ```APIDOC ## Alternative Syntax for Dynamic Components ### Description Provides an alternative syntax for rendering dynamic components using ``. ### Method N/A (Component rendering) ### Endpoint N/A (Component rendering) ### Parameters #### Query Parameters - **component** (string) - Required - The name of the component to render. - **wire:key** (string) - Required - A unique key to ensure proper re-rendering of the dynamic component. ### Request Example ```html ``` ### Response N/A (Component rendering) ``` -------------------------------- ### Sample Livewire Simple Pagination View Source: https://livewire.laravel.com/docs/4.x/pagination An unstyled example of a Livewire pagination view. It demonstrates using Livewire's page navigation helpers like '$this->nextPage()' with 'wire:click' for interactive pagination controls. ```blade
@if ($paginator->hasPages()) @endif
``` -------------------------------- ### Class-Based Component PHP File Source: https://livewire.laravel.com/docs/4.x/components Example of a class-based Livewire component's PHP file structure. ```php bookmarked = $this->post->bookmarkedBy(auth()->user()); } public function bookmarkPost() { $this->post->bookmark(auth()->user()); $this->bookmarked = $this->post->bookmarkedBy(auth()->user()); } }; ``` -------------------------------- ### Testing File Downloads in Livewire Source: https://livewire.laravel.com/docs/4.x/downloads Provides examples for testing file download functionality using the assertFileDownloaded and assertNoFileDownloaded methods in Livewire tests. ```php public function test_can_download_invoice() { $invoice = Invoice::factory(); Livewire::test(ShowInvoice::class) ->call('download') ->assertFileDownloaded('invoice.pdf'); } public function test_does_not_download_invoice_if_unauthorised() { $invoice = Invoice::factory(); Livewire::test(ShowInvoice::class) ->call('download') ->assertNoFileDownloaded(); } ``` -------------------------------- ### Implement a Countdown with wire:stream Source: https://livewire.laravel.com/docs/4.x/wire-stream This example demonstrates a Livewire component that uses the stream method to update a UI element in real-time. It uses a while loop and sleep to simulate a long-running process that updates the browser display incrementally. ```php use Livewire\Component; class CountDown extends Component { public $start = 3; public function begin() { while ($this->start >= 0) { $this->stream( to: 'count', content: $this->start, replace: true, ); sleep(1); $this->start = $this->start - 1; }; } public function render() { return <<<'HTML'

Count: {{ $start }}

HTML; } } ``` -------------------------------- ### Tracking External Links Asynchronously Source: https://livewire.laravel.com/docs/4.x/attribute-async An example of using #[Async] to track user interactions with external links without delaying the navigation experience for the user. ```php use Livewire\Attributes\Async; use Livewire\Component; new class extends Component { public $url; #[Async] public function trackClick() { Analytics::track('external-link-clicked', [ 'url' => $this->url, 'user_id' => auth()->id(), ]); } }; ``` ```blade Visit External Site ``` -------------------------------- ### Configure Content-Security-Policy Headers Source: https://livewire.laravel.com/docs/4.x/csp Example of CSP headers configured for Livewire's CSP-safe build. It emphasizes removing 'unsafe-eval' and utilizing nonce-based script loading with 'strict-dynamic'. ```HTTP Content-Security-Policy: default-src 'self'; script-src 'nonce-[random]' 'strict-dynamic'; style-src 'self' 'unsafe-inline'; ``` -------------------------------- ### Listening for Enter Key Press Source: https://livewire.laravel.com/docs/4.x/actions Example of using `wire:keydown.enter` to trigger a Livewire action ('searchPosts') only when the Enter key is pressed after input. ```blade ``` -------------------------------- ### Async Action for Tracking External Link Clicks Source: https://livewire.laravel.com/docs/4.x/actions This example demonstrates using an async action to track clicks on external links without delaying the user's navigation. The `#[Async]` attribute and `.async` modifier are used. ```php $this->url, 'user_id' => auth()->id(), ]); } // ... }; ``` ```blade Visit External Site ``` -------------------------------- ### Livewire Component State Example (Stringable Property) Source: https://livewire.laravel.com/docs/4.x/synthesizers This PHP code demonstrates a Livewire component with a public property that is a Laravel Stringable. The `mount` method initializes the property as a Stringable, showcasing how Livewire handles such types using Synthesizers. ```php class CreatePost extends Component { public $title = ''; public function mount() { $this->title = str($this->title); } } ``` -------------------------------- ### Configuring Default Placeholder View in Livewire Source: https://livewire.laravel.com/docs/4.x/lazy Provides an example of how to set a default placeholder view for all lazy-loaded Livewire components by configuring the `component_placeholder` option in `config/livewire.php`. This ensures a consistent loading experience. ```php 'component_placeholder' => 'livewire.placeholder', ``` -------------------------------- ### Livewire Browser Test for User Interaction Source: https://livewire.laravel.com/docs/4.x/testing An example of a browser test using Livewire's `visit` method to simulate user interaction, such as typing into fields and submitting a form. ```php it('can create a new post', function () { Livewire::visit('post.create') ->type('[wire\:model="title"]', 'My first post') ->type('[wire\:model="content"]', 'This is the content') ->press('Save') ->assertSee('Post created successfully'); }); ``` -------------------------------- ### Fetch Data for JavaScript Consumption Asynchronously Source: https://livewire.laravel.com/docs/4.x/actions This example shows how to fetch data asynchronously using `#[Async]` for consumption purely by JavaScript (e.g., Alpine.js). The data is not stored in Livewire's component state, making it safe. ```php limit(5) ->pluck('title'); } // ... }; ``` ```blade
``` -------------------------------- ### Accessing Livewire Properties with Alpine $wire Source: https://livewire.laravel.com/docs/4.x/alpine Demonstrates how to use the Alpine $wire object to access and display Livewire component properties in real-time. This example shows a character count for a text input. ```html
Character count:
``` -------------------------------- ### Initialize Component State with mount() Source: https://livewire.laravel.com/docs/4.x/lifecycle-hooks Demonstrates using the mount() method to initialize component properties from the authenticated user or injected models. This method runs only once when the component is first created. ```php use Illuminate\Support\Facades\Auth; use Livewire\Component; new class extends Component { public $name; public $email; public function mount() { $this->name = Auth::user()->name; $this->email = Auth::user()->email; } }; ``` ```php use Livewire\Component; use App\Models\Post; new class extends Component { public $title; public $content; public function mount(Post $post) { $this->title = $post->title; $this->content = $post->content; } }; ``` -------------------------------- ### Valid vs. Invalid @teleport Structure Source: https://livewire.laravel.com/docs/4.x/directive-teleport Highlights the constraint that the @teleport directive requires a single root element within its content. The 'Valid' example shows a single div wrapping the content, while the 'Invalid' example shows multiple root-level elements, which is not supported. ```blade // Valid: @teleport('body')

Title

Content

@endteleport // Invalid: @teleport('body')

Title

Content

@endteleport ``` -------------------------------- ### Initialize Component Properties in Mount Source: https://livewire.laravel.com/docs/4.x/properties Demonstrates how to set initial values for component properties using the mount() lifecycle method. This ensures properties are populated when the component is first rendered. ```php use Livewire\Component; new class extends Component { public $todos = []; public $todo = ''; public function mount() { $this->todos = ['Buy groceries', 'Walk the dog', 'Write code']; } }; ``` -------------------------------- ### Initialize Livewire and Alpine in JavaScript Source: https://livewire.laravel.com/docs/4.x/installation Import Livewire and Alpine into your build process to register plugins and manually trigger initialization. ```js import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm'; import Clipboard from '@ryangjchandler/alpine-clipboard' Alpine.plugin(Clipboard) Livewire.start() ``` -------------------------------- ### Publish Livewire Configuration Source: https://livewire.laravel.com/docs/4.x/installation Run this command to create a livewire.php file in the config directory for custom settings. ```shell php artisan livewire:config ``` -------------------------------- ### Showing a Loading Indicator Source: https://livewire.laravel.com/docs/4.x/forms Provides examples of how to display a loading indicator during form submission. ```APIDOC ## Showing a Loading Indicator By default, Livewire will automatically disable submit buttons and mark inputs as `readonly` while a form is being submitted, preventing the user from submitting the form again while the first submission is being handled. However, it can be difficult for users to detect this "loading" state without extra affordances in your application's UI. ### Using `wire:loading` Here's an example of adding a small loading spinner to the "Save" button via `wire:loading` so that a user understands that the form is being submitted: ### Request Example ```html ``` ### Using Tailwind CSS and `data-loading` attribute Alternatively, you can use Tailwind and Livewire's automatic `data-loading` attribute for cleaner markup: ### Request Example ```html ``` [Learn more about loading states →](/docs/4.x/loading-states) ``` -------------------------------- ### Initialize Component Properties with boot() Source: https://livewire.laravel.com/docs/4.x/lifecycle-hooks The boot method runs on every request to the server, making it ideal for initializing non-persisted properties like Eloquent models. It is recommended to use the #[Locked] attribute for sensitive properties to prevent client-side tampering. ```php use Livewire\Attributes\Locked; use Livewire\Component; use App\Models\Post; new class extends Component { #[Locked] public $postId = 1; protected Post $post; public function boot() { $this->post = Post::find($this->postId); } }; ``` -------------------------------- ### Install Livewire v4 Source: https://livewire.laravel.com/docs/4.x/upgrading Update your composer.json to require Livewire v4 and clear the application cache. ```bash composer require livewire/livewire:^4.0 ``` ```bash php artisan optimize:clear ``` -------------------------------- ### Initialize Livewire Component Tests Source: https://livewire.laravel.com/docs/4.x/testing Methods to instantiate a Livewire component for testing, optionally passing parameters to the mount method. ```php Livewire::test('post.create'); Livewire::test(UpdatePost::class, ['post' => $post]); ``` -------------------------------- ### Test File Uploads in Livewire Source: https://livewire.laravel.com/docs/4.x/uploads This example demonstrates how to test Livewire file uploads using Laravel's built-in testing helpers. It includes setting up a fake storage disk, creating a fake uploaded file, and asserting that the file exists after the upload process. ```PHP image('avatar.png'); Livewire::test(UploadPhoto::class) ->set('photo', $file) ->call('upload', 'uploaded-avatar.png'); Storage::disk('avatars')->assertExists('uploaded-avatar.png'); } } ``` ```PHP photo->storeAs('/', $name, disk: 'avatars'); } // ... }; ``` -------------------------------- ### Generate and Configure Layouts Source: https://livewire.laravel.com/docs/4.x/pages Commands and configuration for setting up the default application layout file used by Livewire components. ```shell php artisan livewire:layout ``` ```php 'component_layout' => 'layouts::dashboard', ``` -------------------------------- ### Simplified Snapshot State Source: https://livewire.laravel.com/docs/4.x/hydration An example of a naive state representation that lacks the necessary metadata for proper hydration. ```js state: { todos: [ 'first', 'second', 'third' ], }, ``` -------------------------------- ### Livewire Component Update Payload Source: https://livewire.laravel.com/docs/4.x/hydration Example of the JSON payload sent to the server when a component update is triggered. ```js { calls: [ { method: 'increment', params: [] }, ], snapshot: { state: { count: 1, }, memo: { name: 'counter', id: '1526456', }, } } ``` -------------------------------- ### Property binding syntax Source: https://livewire.laravel.com/docs/4.x/wire-model Examples of various ways to bind properties, including nested objects and array indices. ```blade wire:model="propertyName" wire:model="property.nested" wire:model="property['nested']" wire:model="property[0]" ``` -------------------------------- ### Example Dehydrated Model JSON Source: https://livewire.laravel.com/docs/4.x/properties Shows the structure of a serialized Livewire model property before and after applying a morphMap alias. ```json { "type": "model", "class": "App\Models\Post", "key": 1, "relationships": [] } ``` -------------------------------- ### Bundling Deferred Livewire Components Source: https://livewire.laravel.com/docs/4.x/attribute-defer Illustrates how to bundle multiple deferred Livewire components into a single network request using the `bundle: true` parameter within the `#[Defer]` attribute. This optimization reduces the number of HTTP requests, especially when many deferred components are present on the same page, improving loading efficiency. ```php ``` -------------------------------- ### Dynamically Control Transitions with transition() Method in PHP Source: https://livewire.laravel.com/docs/4.x/attribute-transition Demonstrates the imperative approach to controlling view transitions using the `transition()` method within a Livewire component. This method allows for dynamic setting of transition types based on runtime logic, such as comparing current and target step values. ```php transition(type: $step > $this->step ? 'forward' : 'backward'); $this->step = $step; } ``` -------------------------------- ### Embed Snapshot in HTML Source: https://livewire.laravel.com/docs/4.x/hydration Example of how the JSON snapshot is stored within the wire:snapshot attribute in the rendered HTML. ```html
Count: 1
``` -------------------------------- ### Livewire Component PHP Example Source: https://livewire.laravel.com/docs/4.x/javascript A basic Livewire component written in PHP. This serves as the server-side counterpart to the JavaScript interactions. ```php count++; } public function render() { return view('livewire.counter'); } } ``` -------------------------------- ### Create Livewire Components Source: https://livewire.laravel.com/docs/4.x/upgrading Use the Artisan CLI to generate single-file or multi-file Livewire components. The `--mfc` flag enables multi-file components. ```bash php artisan make:livewire create-post # Single-file (default) php artisan make:livewire create-post --mfc # Multi-file php artisan livewire:convert create-post # Convert between formats ``` -------------------------------- ### Class-Based Component Blade View File Source: https://livewire.laravel.com/docs/4.x/components Example of a class-based Livewire component's Blade view file structure. ```blade
{{-- ... --}}
``` -------------------------------- ### Listen for Livewire Events Globally with JavaScript Source: https://livewire.laravel.com/docs/4.x/events This code demonstrates how to listen for Livewire events ('post-created') from any script in your application using `Livewire.on`. It includes the necessary `livewire:init` event listener and shows how to optionally unregister the listener using the returned cleanup function. ```html document.addEventListener('livewire:init', () => { Livewire.on('post-created', (event) => { // }); }); ``` ```html document.addEventListener('livewire:init', () => { let cleanup = Livewire.on('post-created', (event) => { // }); // Calling "cleanup()" will un-register the above event listener... cleanup(); }); ``` -------------------------------- ### Enable Smart Wire:key Behavior Source: https://livewire.laravel.com/docs/4.x/upgrading The 'smart_wire_keys' configuration now defaults to true in v4, helping prevent issues with deeply nested components. Manual 'wire:key' is still required in loops. ```php // Now defaults to true (was false in v3) 'smart_wire_keys' => true, ``` -------------------------------- ### Configure custom and dynamic session keys Source: https://livewire.laravel.com/docs/4.x/attribute-session Shows how to define explicit session keys or generate them dynamically based on other component properties for granular state control. ```php use Livewire\Attributes\Session; use Livewire\Component; use App\Models\Author; new class extends Component { #[Session(key: 'post_search')] public $search = ''; public Author $author; #[Session(key: 'search-{author.id}')] public $dynamicSearch = ''; }; ``` -------------------------------- ### Client-Side Event Dispatching Source: https://livewire.laravel.com/docs/4.x/nesting This example demonstrates how to dispatch a Livewire event directly from the client-side within a component, avoiding an initial network request. ```APIDOC ## Client-Side Event Dispatching ### Description This example shows how to dispatch a Livewire event directly from the client-side to improve performance by avoiding an unnecessary network request. ### Method N/A (Client-side action) ### Endpoint N/A (Client-side action) ### Parameters N/A ### Request Example ```php
{{ $todo->content }}
``` ### Response N/A (Client-side action) ``` -------------------------------- ### Create a Page Component Source: https://livewire.laravel.com/docs/4.x/components Use the `pages::` namespace with the `make:livewire` command to create components intended for full-page usage. This organizes them in the `resources/views/pages/` directory. ```shell php artisan make:livewire pages::post.create ``` -------------------------------- ### Downloading Files via Storage Facade Source: https://livewire.laravel.com/docs/4.x/downloads Shows how to download files stored on specific disks using the Laravel Storage facade within a Livewire component. ```php public function download() { return Storage::disk('invoices')->download('invoice.csv'); } ``` -------------------------------- ### Listen for and Dispatch Events in Livewire Source: https://livewire.laravel.com/docs/4.x/attribute-on Demonstrates how to use the #[On] attribute to listen for events and the dispatch method to trigger them. This pattern allows for decoupled communication between components. ```php use Livewire\Attributes\On; use Livewire\Component; class Dashboard extends Component { #[On('post-created')] public function updatePostList($title) { session()->flash('status', "New post created: {$title}"); } } // Dispatching the event $this->dispatch('post-created', title: 'My New Post'); ``` -------------------------------- ### Enable Data Binding with Synthesizer Source: https://livewire.laravel.com/docs/4.x/synthesizers Extends the Synthesizer with get and set methods to allow wire:model binding directly to object properties. ```php public function get(&$target, $key) { return $target->{$key}; } public function set(&$target, $key, $value) { $target->{$key} = $value; } ``` -------------------------------- ### Disabling Lazy Loading for Tests Source: https://livewire.laravel.com/docs/4.x/lazy Provides an example of how to disable lazy loading during tests using `Livewire::withoutLazyLoading()` to ensure components render fully. ```APIDOC ## Disabling Lazy Loading for Tests ### Description When unit testing a lazy component, or a page with nested lazy components, you may want to disable the "lazy" behavior so that you can assert the final rendered behavior. Otherwise, those components would be rendered as their placeholders during your tests. You can easily disable lazy loading using the `Livewire::withoutLazyLoading()` testing helper. ### Method Testing helper ### Endpoint N/A (Testing context) ### Request Example ```php test(Dashboard::class) ->assertSee(...); } } ``` ### Response N/A ``` -------------------------------- ### Create a Multi-File Livewire Component Source: https://livewire.laravel.com/docs/4.x/components Generate a multi-file component using the `--mfc` flag with the `make:livewire` command. This separates the component's PHP, Blade, JavaScript, and CSS into distinct files within a dedicated directory. ```shell php artisan make:livewire post.create --mfc ``` -------------------------------- ### Use Class-Based Components (v3 Convention) Source: https://livewire.laravel.com/docs/4.x/components To adopt v3 conventions and generate class-based components by default, configure `config/livewire.php` with `'type' => 'class'` and `'emoji' => false`. ```php return [ // ... 'make_command' => [ 'type' => 'class', 'emoji' => false, ], // ... ]; ``` -------------------------------- ### Invoke Magic Actions from Alpine.js Source: https://livewire.laravel.com/docs/4.x/actions Call Livewire magic actions from Alpine.js components using the `$wire` object. This example demonstrates invoking the `$refresh` action. ```html ``` -------------------------------- ### Redirect to a Controller Action in Livewire Source: https://livewire.laravel.com/docs/4.x/redirecting This example demonstrates redirecting to a route handled by a controller action using the `redirectAction` method. Parameters can be passed as the second argument. ```php $this->redirectAction([UserController::class, 'index']); ``` ```php $this->redirectAction([UserController::class, 'show'], ['id' => 1]); ``` -------------------------------- ### Configure Make Command Defaults Source: https://livewire.laravel.com/docs/4.x/upgrading Customize the default component format ('sfc', 'mfc', or 'class') and emoji prefix for the 'make' command. ```php 'make_command' => [ 'type' => 'sfc', // Options: 'sfc', 'mfc', or 'class' 'emoji' => true, // Whether to use ⚡ emoji prefix ], ``` -------------------------------- ### Product Filtering Component Source: https://livewire.laravel.com/docs/4.x/attribute-url An example Livewire component demonstrating product filtering with various URL parameters like search, category, price range, and sorting. ```APIDOC ## POST /websites/livewire_laravel_4_x/products ### Description This example demonstrates a Livewire component that filters products based on URL query parameters. Users can search, filter by category, set a price range, and sort the results. The component uses the `#[Url]` attribute to synchronize component properties with the browser's URL query string. ### Method GET (Implicitly via Livewire component rendering) ### Endpoint /websites/livewire_laravel_4_x/products ### Parameters #### Query Parameters - **q** (string) - Optional - The search query for products. - **category** (string) - Optional - The category to filter products by. Defaults to 'all'. - **minPrice** (integer) - Optional - The minimum price for product filtering. Defaults to 0. - **maxPrice** (integer) - Optional - The maximum price for product filtering. Defaults to 1000. - **sort** (string) - Optional - The field to sort products by. Defaults to 'name'. ### Request Example (This is a client-side component, no direct request body example is applicable. The filtering is driven by URL parameters.) ### Response #### Success Response (200) - **products** (Paginated Collection) - A paginated list of products matching the filter criteria. #### Response Example (HTML output rendered by Livewire, containing product listings based on the applied filters.) ## Learn More For more information about URL query parameters and Livewire, refer to the [URL Query Parameters documentation](/docs/4.x/url). ``` -------------------------------- ### Implement persistent dashboard filters Source: https://livewire.laravel.com/docs/4.x/attribute-session A practical example of using multiple #[Session] attributes to maintain complex dashboard filtering state across user sessions. ```php use Livewire\Attributes\Session; use Livewire\Attributes\Computed; use Livewire\Component; use App\Models\Transaction; new class extends Component { #[Session] public $dateRange = '30days'; #[Session] public $category = 'all'; #[Session] public $sortBy = 'date'; #[Computed] public function transactions() { return Transaction::query() ->when($this->dateRange === '30days', fn($q) => $q->where('created_at', '>=', now()->subDays(30))) ->when($this->category !== 'all', fn($q) => $q->where('category', $this->category)) ->orderBy($this->sortBy) ->get(); } }; ``` -------------------------------- ### Public Method Vulnerability Example Source: https://livewire.laravel.com/docs/4.x/actions This PHP snippet demonstrates a public method 'deletePost' that calls a public 'delete' method, which is vulnerable to client-side invocation. Avoid this pattern. ```php posts; } public function deletePost($id) { if (! Auth::user()->isAdmin) { abort(403); } $this->delete($id); // [tl! highlight] } public function delete($postId) // [tl! highlight:5] { $post = Post::find($postId); $post->delete(); } }; ``` -------------------------------- ### Enable Lazy Loading for Livewire Components Source: https://livewire.laravel.com/docs/4.x/lazy Demonstrates how to implement a component with a slow mount process and how to invoke it using the lazy attribute in a Blade template. ```php use Livewire\Component; use App\Models\Transaction; new class extends Component { public $amount; public function mount() { $this->amount = Transaction::monthToDate()->sum('amount'); } }; ``` ```blade ``` -------------------------------- ### Using the #[Url] Attribute Source: https://livewire.laravel.com/docs/4.x/attribute-url The #[Url] attribute is applied to component properties to automatically sync them with the URL query string. This example demonstrates basic usage for a search input. ```APIDOC ## #[Url] Attribute Usage ### Description Synchronizes a component property with the URL query string. When the property changes, the URL updates; when the page loads, the property is initialized from the URL. ### Usage Apply the attribute to any public property within a Livewire component. ### Configuration Options - **as** (string) - Optional - Alias for the property name in the URL (e.g., `#[Url(as: 'q')]`). - **except** (mixed) - Optional - Value to exclude from the URL. - **keep** (boolean) - Optional - If true, always include the parameter in the URL even if empty. - **history** (boolean) - Optional - If true, adds entries to browser history for back/forward navigation. ### Example ```php use Livewire\Attributes\Url; use Livewire\Component; class SearchComponent extends Component { #[Url(as: 'q', history: true)] public $search = ''; } ``` ``` -------------------------------- ### Configure persistent and global caching Source: https://livewire.laravel.com/docs/4.x/attribute-computed Examples of using the persist and cache parameters to extend the lifetime of computed properties across requests or across different component instances. ```php #[Computed(persist: true, seconds: 7200)] public function user() { ... } #[Computed(cache: true, key: 'homepage-posts')] public function posts() { ... } ``` -------------------------------- ### Livewire Post Creation Component (PHP - Production) Source: https://livewire.laravel.com/docs/4.x/quickstart This is a production-ready version of the Livewire save method, demonstrating how to persist validated data to a database using a Post model and redirect the user. It assumes a 'Post' Eloquent model and a corresponding database table. ```php public function save() { $validated = $this->validate([ 'title' => 'required|max:255', 'content' => 'required', ]); Post::create($validated); // Assumes you have a Post model and database table return $this->redirect('/posts'); } ``` -------------------------------- ### Generate Livewire Component Test File Source: https://livewire.laravel.com/docs/4.x/testing Artisan command to generate a test file alongside a new Livewire component. This simplifies the setup for testing individual components. ```shell php artisan make:livewire post.create --test ``` -------------------------------- ### Implementing Wireable Interface in PHP Source: https://livewire.laravel.com/docs/4.x/properties Demonstrates how to make a custom class (e.g., Customer) compatible with Livewire by implementing the Wireable interface. This involves adding `toLivewire()` and `fromLivewire()` methods to handle serialization and deserialization between PHP objects and JSON. ```php class Customer { protected $name; protected $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } } ``` ```php use Livewire\Wireable; class Customer implements Wireable { protected $name; protected $age; public function __construct($name, $age) { $this->name = $name; $this->age = $age; } public function toLivewire() { return [ 'name' => $this->name, 'age' => $this->age, ]; } public static function fromLivewire($value) { $name = $value['name']; $age = $value['age']; return new static($name, $age); } } ``` -------------------------------- ### Defining a Parent Component with Nested Children Source: https://livewire.laravel.com/docs/4.x/understanding-nesting Example of a parent Blade component that uses wire:model.live to trigger updates and nests child components using the livewire directive. ```blade
Post Limit: @foreach ($posts as $post) @endforeach
``` -------------------------------- ### Configure Additional Component Locations Source: https://livewire.laravel.com/docs/4.x/components Specify additional directories in `config/livewire.php` where Livewire should automatically discover components. ```php 'component_locations' => [ resource_path('views/components'), resource_path('views/admin/components'), resource_path('views/widgets'), ], ``` -------------------------------- ### Livewire Component Update Payload Source: https://livewire.laravel.com/docs/4.x/understanding-nesting Example of the JSON payload sent to the server when a child component triggers an update. It highlights that only the specific child component's state is transmitted. ```json { "memo": { "name": "show-post", "id": "456" }, "state": { ... } } ```