Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I customize the keep-alive component in Laravel Splade


Can I customize the keep-alive component in Laravel Splade


Yes, you can customize the behavior of the `keep-alive` component in Laravel Splade. Here are a few ways you can do this:

1. Configuring the `max_keep_alive` option:
As mentioned in the documentation, you can configure the maximum number of pages to keep alive by setting the `max_keep_alive` option when registering the Splade plugin:

javascript
createApp({ render: renderSpladeApp({ el }) })
  .use(SpladePlugin, {
    'max_keep_alive': 50,
  })
  .mount(el);

This will increase the number of pages kept in memory from the default of 10 to 50.

2. Disabling `keep-alive` for specific components:
If you have certain components that you don't want to be kept alive, you can disable the `keep-alive` behavior for those components. You can do this by adding the `no-keep-alive` directive to the component:

html
<x-splade-component no-keep-alive>
  <!-- Your component content -->
</x-splade-component>

This will ensure that the component is not kept in memory when navigating away from the page.

3. Customizing the `keep-alive` behavior:
If you need more fine-grained control over the `keep-alive` behavior, you can create a custom Blade component that extends the `ProtoneMedia\Splade\Components\PersistentComponent` class. This allows you to override the `shouldBeKeptAlive()` method and implement your own logic for determining when a component should be kept alive.

php
use ProtoneMedia\Splade\Components\PersistentComponent;

class CustomPersistentComponent extends PersistentComponent
{
    public function shouldBeKeptAlive(): bool
    {
        // Implement your custom logic here
        return $this->shouldKeepAlive;
    }

    public function render()
    {
        return view('components.custom-persistent');
    }
}

Then, in your Blade template, you can use the custom component:

html
<x-custom-persistent>
  <!-- Your component content -->
</x-custom-persistent>

By using these techniques, you can fine-tune the behavior of the `keep-alive` component in your Laravel Splade application to suit your specific needs.

Citations:
[1] https://github.com/protonemedia/laravel-splade/blob/main/CHANGELOG.md
[2] https://splade.dev/docs/breeze
[3] https://splade.dev/docs/persistent-layout
[4] https://www.reddit.com/r/laravel/comments/w5dmvt/laravel_splade_the_magic_of_inertiajs_with_the/
[5] https://splade.dev/docs/state-management