Overview Passing data from the server to your frontend template is the heartbeat of any Livewire application. While the framework offers multiple entry points, choosing the wrong one can lead to unnecessary database pressure or state bugs. Understanding the lifecycle timing of these methods ensures your Laravel applications remain performant and scalable. Prerequisites To get the most out of this guide, you should be comfortable with PHP and the basics of Laravel. Familiarity with Eloquent models and basic Livewire component structure is highly recommended. Key Libraries & Tools * Livewire: A full-stack framework for Laravel that builds dynamic interfaces. * Eloquent: The database ORM used to fetch data. * Laravel Debugbar: A vital package for monitoring database query counts during development. Code Walkthrough The Render Method The `render()` method acts like a traditional controller. It runs on the initial load and **every single subsequent update**. ```php public function render() { return view('livewire.bookmarks', [ 'bookmarks' => Bookmark::all(), ]); } ``` Use this when data must refresh every time a user interacts with the component. The Mount Hook Think of `mount()` as your constructor. It runs **only once** when the component is first initialized. ```php public function mount(Bookmark $bookmark) { $this->bookmark = $bookmark; } ``` This is the perfect spot for Route Model Binding. Since it doesn't rerun, it saves resources on subsequent clicks. Computed Properties Computed properties offer a "lazy loading" approach. They only execute the query if the template actually requests the data. ```php #[Computed(persist: true, seconds: 3600)] public function bookmarks() { return Bookmark::all(); } ``` By using `#[Computed]`, Livewire caches the result for the duration of the request, preventing duplicate queries if you access the property multiple times. Syntax Notes When using computed properties, you cannot access them as standard public properties. You must use the `$this` prefix in your Blade templates, such as `$this->bookmarks` instead of just `$bookmarks`. Practical Examples Use **Mount** for editing a specific record where the ID won't change. Use **Render** for a live search results list. Use **Computed Properties** for expensive dashboard stats that might be hidden behind authorization checks or tabs. Tips & Gotchas A common mistake is fetching large datasets in `render()`. If your component has many inputs, every keystroke triggers a re-render and a fresh database query. If you need persistence beyond the immediate request, the `persist: true` attribute on a computed property is a lifesaver.
Route Model Binding
Concepts
- Jul 2, 2024
- Nov 30, 2023