vm-engine / wire-util
Shared Livewire and Eloquent traits: session-bound delete tokens, remembered list filters, sortable pagination and safe return URLs
Requires
- php: ^8.3
- laravel/framework: ^13.0
- livewire/livewire: ^4.0
Requires (Dev)
- larastan/larastan: ^3.0
- laravel/pint: ^1.0
- orchestra/testbench: ^11.0
- pestphp/pest: ^5.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
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:
WithDeleteToken: encrypted, session-bound delete tokens instead of raw idsRemembersQueryParams: list filters survive navigating away and backWithSortablePagination: sortable columns and page size, validatedWithReturnUrl: "back to where I came from" after saving a form
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}; overriderememberKey()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,$sortDirectionand$perPageare client-writable, so query with thevalidated*()methods, never the raw properties. An unknown column falls back toid, a bad direction todesc, and a page size outsideallowedPerPage()(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) becomesVmEngine\WireUtil\…. RemembersQueryParamsstores underwire-util:query_params:instead ofwebms:query_params:, so remembered filters start fresh once. Thewebms-restored-querybrowser 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.
WithSortablePaginationnow needsWithPaginationand resets the page on sort and page-size changes; query withvalidatedPerPage().
Licence
MIT. See LICENSE.