Search by

vm-engine / wire-util

adods

Shared Livewire and Eloquent traits: session-bound delete tokens, remembered list filters, sortable pagination and safe return URLs

Package info

github.com/vm-engine/wire-util

pkg:composer/vm-engine/wire-util

Statistics

Installs: 2

Dependents: 1

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0 2026-11-17 07:06 UTC

This package is auto-updated.

Last update: 2026-12-04 14:59:36 UTC


README

Small, dependency-free traits for Livewire 4 list and form pages and Eloquent models:

Traits only: no service provider, config, views or JavaScript to publish.

Requirements

  • PHP 8.3+
  • Laravel 13
  • Livewire 4

Installation

composer require vm-engine/wire-util

WithDeleteToken

Delete buttons never print a record id. Each model gets a delete_token. It is encrypted and authenticated with keys derived from APP_KEY, bound to the user's session, and bound to the model class, so a token for a Post never deletes a User with the same id.

use VmEngine\WireUtil\WithDeleteToken;

class Post extends Model
{
    use WithDeleteToken;
}
// Livewire component
public function delete(string $token): void
{
    $id = Post::validateDeleteToken($token);

    if ($id === false) {
        $this->dispatch('notify', message: __('Invalid delete token.'));

        return;
    }

    $post = Post::query()->findOrFail($id);
    $this->authorize('delete', $post);   // tokens prove intent, not permission
    $post->delete();
}
{{-- with vm-engine/ui-kit --}}
<x-ui::confirm-button method="delete" :token="$post->delete_token"
    :label="__('Delete')" :title="__('Delete post?')" :message="__('This cannot be undone.')" />

delete_token is appended to retrieved models but hidden from toArray()/JSON, so print it explicitly.

Bulk delete. A record's token stays the same for the whole session, so tokens work as checkbox values:

<flux:checkbox wire:model.live="selected" value="{{ $post->delete_token }}" />
public array $selected = [];

public function deleteSelected(): void
{
    $ids = Post::validateDeleteTokens($this->selected);   // all-or-nothing

    if ($ids === false) {
        $this->dispatch('notify', message: __('Invalid delete token.'));

        return;
    }

    Post::query()->whereKey($ids)->get()->each(fn (Post $post) => $this->authorize('delete', $post));
    Post::query()->whereKey($ids)->delete();
    $this->selected = [];
}

One forged token rejects the whole selection, so nothing runs.

RemembersQueryParams

Remembers chosen properties in the session, so a list comes back with its search, filters and page when the user returns through a breadcrumb or the back button.

use Livewire\Attributes\Url;
use VmEngine\WireUtil\RemembersQueryParams;

class PostList extends Component
{
    use RemembersQueryParams;

    #[Url(as: 'q')]
    public string $search = '';

    #[Url]
    public string $status = 'all';

    protected function rememberedParams(): array
    {
        return ['search', 'status'];
    }

    public function clearFilters(): void
    {
        $this->reset(['search', 'status']);
        $this->forgetRememberedParams();
    }
}
  • The URL wins. A param in the URL is never overwritten, so bookmarks and shared links work. Components mounted during a Livewire update request (lazy, nested) read the page URL from the Referer.
  • The address bar follows. Restored values are written back into the URL with history.replaceState, through Livewire's $this->js(), so no host JavaScript is needed. #[Url(as: ...)] aliases, arrays and booleans are written the way Livewire reads them back.
  • A stored value that no longer fits its property (say, a deploy changed the type) is skipped, and the property keeps its default.
  • forgetRememberedParams() clears the session copy and skips saving for the rest of that request; the next request remembers again.
  • getRememberedParamValues() reads the stored values without applying them.
  • The session key is wire-util:query_params:{component class}; override rememberKey() to change it.

WithSortablePagination

Sortable columns and a page-size choice for list components. Use it together with Livewire's WithPagination; it is required.

use Livewire\WithPagination;
use VmEngine\WireUtil\WithSortablePagination;

class PostList extends Component
{
    use WithPagination;
    use WithSortablePagination;

    protected function allowedSortFields(): array
    {
        return ['id', 'title', 'created_at'];
    }

    public function render(): View
    {
        return view('livewire.post-list', [
            'posts' => Post::query()
                ->orderBy($this->validatedSortField(), $this->validatedSortDirection())
                ->paginate($this->validatedPerPage()),
        ]);
    }
}
<flux:table.column sortable :sorted="$sortField === 'title'" :direction="$sortDirection"
    wire:click="sortBy('title')">Title</flux:table.column>

{{-- with vm-engine/ui-kit: binds $perPage --}}
<x-ui::per-page-selector :paginator="$posts" />
  • $sortField, $sortDirection and $perPage are client-writable, so query with the validated*() methods, never the raw properties. An unknown column falls back to id, a bad direction to desc, and a page size outside allowedPerPage() (default [10, 15, 25, 50]) to 15, or to the first allowed size if 15 isn't offered.
  • sortBy($field) toggles the direction on the same column and starts a new column ascending.
  • Changing the sort or the page size goes back to page 1. Reset the page yourself when your own filters change.

WithReturnUrl

Link to a form with ?back= and return there after saving:

<flux:button :href="route('posts.edit', ['post' => $post, 'back' => request()->fullUrl()])">Edit</flux:button>
use VmEngine\WireUtil\WithReturnUrl;

class PostForm extends Component
{
    use WithReturnUrl;

    public function save(): void
    {
        // ...
        $this->redirectBack('posts.index');
    }
}

redirectBack($defaultRoute, $parameters) follows ?back= only when it is a same-origin path (/posts?page=2) or an absolute URL with the app's scheme, host and port. Anything else goes to the default route: other hosts, //host, javascript:, URLs with control characters or whitespace (browsers strip tab and newline, turning /\t/evil.test into //evil.test), and any URL with a backslash. Browsers read \ as /, so /\evil.test and http://evil.test\@your-app.test leave the site; a real URL carries it as %5C.

Migrating from the webms or file-manager copies

  • Change the namespace: VmEngine\WebMS\Concerns\… (or the file-manager equivalent) becomes VmEngine\WireUtil\….
  • RemembersQueryParams stores under wire-util:query_params: instead of webms:query_params:, so remembered filters start fresh once. The webms-restored-query browser event is gone; the URL is synced by the trait itself.
  • Delete tokens from the old copy don't validate with this one. Tokens only live for one session, so this only affects pages that were open during the deploy.
  • WithSortablePagination now needs WithPagination and resets the page on sort and page-size changes; query with validatedPerPage().

Licence

MIT. See LICENSE.