One tag-filtered listing in Laravel PHP
Scope
Inline one any-tags read against the existing polymorphic pivot using native query-builder whereExists. Accept two already-resolved IDs and a non-null type. Exclude translated string resolution, custom tag models, writes, all-tags/without-tags, ordered tag hydration and lifecycle hooks. Preserve Spatie's MIT notice when adapting code. Check get-recipe's current port catalog for alternatives. This guidance has not been exercised in your app; verify it below.
Source behaviour
src/HasTags.php::scopeWithAnyTags converts inputs to tags and applies whereHas with their IDs. scopeWithAllTags instead adds one existence predicate per tag. tags() uses configurable morph/table/pivot classes and ordering. src/Tag.php::findManyFromString filters exact type and groups locale-specific name or slug matches; null type there selects null, not every type. tests/HasTagsScopesTest.php exercises any/all, unknown strings and types.
This extraction deliberately moves the API to resolved IDs of one named non-null type and adds an application-specific tenant/deletion rule. Raw subqueries do not inherit a custom Tag model's global scopes. Keep or explicitly reproduce those scopes and input-resolution rules before switching their callers.
Implementation
- Inventory scope calls and compare ordered result/count fixtures. Resolve configured tables/keys/morph alias and custom global scopes. Keep attach/detach/sync, queued tags, model deletion hooks and tag-hydration consumers package-backed.
- Authorize the listing and resolve tag IDs through the app's visibility/type policy. Derive tenant and morph alias from trusted actor/configuration. Default upstream tags may be shared; do not invent a tenant column. Preserve the endpoint's missing/forbidden disclosure policy.
- Apply a native existence predicate to the scoped parent builder before count/pagination. This example uses two IDs; for arbitrary bounded input use native
whereIn, including empty-list behavior, and never skip the filter on empty any-tags. Do not concatenate request values into SQL identifiers or operators. - Keep all parent scopes and reproduce any related-model scopes that the raw subquery would bypass.
EXISTSretains one parent despite multiple matching pivots. Preserve ordering, resource projection, pagination and the actual morph discriminator fromgetMorphClass()or equivalent trusted configuration. - This read needs no migration/write transaction/cache. Retain existing read isolation and cache scoping if applicable. Validate the production driver's plan and current indexes separately. Do not remove the package until all excluded consumers are replaced.
Fragment for an existing action with $tenantId, $morphAlias, $firstTagId, $secondTagId and $tagType already trusted/authorized. Tables are the illustrated schema; use the app's scoped Eloquent parent builder instead if it owns additional scopes. All identifiers are literal and all values are bound:
$posts = \Illuminate\Support\Facades\DB::table('posts as p')
->where('p.tenant_id', $tenantId)
->whereNull('p.deleted_at')
->whereExists(function (\Illuminate\Database\Query\Builder $q) use (
$morphAlias, $firstTagId, $secondTagId, $tagType
) {
$q->selectRaw('1')->from('taggables as pt')
->join('tags as t', 't.id', '=', 'pt.tag_id')
->whereColumn('pt.taggable_id', 'p.id')
->where('pt.taggable_type', $morphAlias)
->whereIn('t.id', [$firstTagId, $secondTagId])
->where('t.type', $tagType);
})
->orderBy('p.id')
->get(['p.id', 'p.title']);
Acceptance checklist
- Compare exact ordered IDs/counts with the original scope: either of IDs 11/12 matches; both attached still returns one parent; duplicate selections do not duplicate rows. Empty any-tags and unknown IDs match nothing.
- Seed another morph alias with the same numeric parent ID, another tenant, a deleted parent, a wrong-type tag and an untagged parent. None leaks into results.
- Verify custom Tag scopes, name-versus-slug matches, locale and null-type differences before changing a string-input endpoint. Do not treat ID-only filtering as a compatible resolver.
- Test real authorization, bound hostile strings, count/page boundaries, JSON projections and actual database plan. Existing writes/deletion hooks and ordered relations must remain unchanged.
- Search trait/scopes/helpers and
composer why spatie/laravel-tagsbefore removal. Run the application's database/request tests, recording source/framework versions, exact results and deliberate API differences.
Sources
- MIT reference:
src/HasTags.php,src/Tag.php,tests/HasTagsScopesTest.php,LICENSE.md. - Framework source checked:
src/Illuminate/Database/Query/Builder.php(whereExists,whereIn,whereColumn) and Eloquent model scopes. Reconcile with the app's lockfile. - Port options: check
get-recipe's current port catalog (sourced from Package Port) at implementation time.