App-owned relationship joins in Laravel PHP
Scope
Inline one package-backed belongsTo join in an authorized listing using Laravel's native query builder. Keep its keys, join type, parent cardinality, projections and transport shape. Do not recreate relationship-name resolution, nested/polymorphic/pivot/to-many joins or aggregate sorting. Keep other package-backed callers until their behaviour has an explicit replacement. Retain the MIT notice for adapted source.
Check get-recipe's current port catalog when considering another implementation. This guidance has not been exercised in your app; verify it with the checks below.
Source behaviour
The inspected src/Mixins/JoinRelationship.php resolves relationship names, handles aliases and repeated joins, and supplies a base-table-only default selection when the caller has not selected columns. It does not populate the Eloquent relationship cache just by joining a table.
src/Mixins/RelationshipsExtraMethods.php::performJoinForEloquentPowerJoinsForBelongsTo joins foreign/owner keys and adds applicable soft-delete and supported relationship conditions inside the join unless disabled. PowerJoinClause::withGlobalScopes is explicit; a native leftJoin does not inherit the joined model's Eloquent global scopes. The source tests demonstrate explicit global-scope callbacks and soft-delete overrides, so inventory those at the real caller rather than assuming every scope is automatic.
Implementation
- Capture the original query's SQL, bindings, model scopes, relationship keys, join callbacks, aliases, selected fields, ordering and pagination. Begin with the existing authorized Eloquent builder to retain its base-model scopes. Qualify any scope columns made ambiguous by the join.
- Replace only the chosen call with
joinorleftJoinon a fixed table/alias and a native join callback. Copy each required related tenant/visibility/deletion predicate explicitly, including deliberatewithTrashed/onlyTrashedbehaviour. NeitherDB::tablenor a joined table applies that related model's scopes automatically. - Keep related eligibility predicates in
ONwhen the intended left join preserves parents without an eligible relation. Moving them toWHEREchanges results. Conversely, preserve an inner join or existence filter when an eligible related record is required. Strengthening a previously incomplete tenant policy is a deliberate behaviour change to record and test. - Select parent fields explicitly and alias related fields without colliding with model attributes. Prove the owner key's uniqueness; don't suppress multiplied rows with
DISTINCT. Use fixed, allowlisted SQL identifiers and bound values. If only existence is needed, a scopedwhereHas/whereExistsmay be simpler, but compare it as a deliberate implementation substitution rather than claiming SQL parity. - Keep null related values nullable in the resource, not empty strings. Joining does not mean
relationLoaded()is true. Preserve stable parent-key tie-breakers and count/page semantics, and check for lazy-loading N+1 queries in resources. A read-only extraction requires no new transaction or migration; preserve an existing snapshot contract if present. Include tenant/permission/filter/page identity in any cache and invalidate changed related projections through existing mechanisms.
Fragment for an already authorized $posts Eloquent builder, assuming an app-owned posts.author_id relationship to unique authors.id and tenant_id/deleted_at on both tables. Additional application policies and the resource remain the caller's responsibility. The join keeps parents while hiding deleted or cross-tenant authors:
use Illuminate\Database\Query\JoinClause;
$posts->leftJoin('authors as a', function (JoinClause $join): void {
$join->on('a.id', '=', 'posts.author_id')
->on('a.tenant_id', '=', 'posts.tenant_id')
->whereNull('a.deleted_at');
})->select(['posts.id', 'posts.title', 'a.name as author_name'])
->orderBy('posts.id');
The fragment does not add the base tenant predicate: it assumes the supplied builder already enforces it. If the original endpoint requires an eligible author, this left-join fragment is not its replacement without an intentional contract change.
Acceptance checklist
- In tenant 1, create two posts sharing one live author, a null-author post, a deleted-author post and a cross-tenant-author post. Add a deleted parent and tenant 2's parent. With the illustrated policy and scoped base query, expect five parents once each; null/deleted/foreign author names are null, and excluded parents do not appear.
- Compare original IDs, projected values, bindings and totals for the actual inner/left variant. Verify custom keys, relation callbacks and any explicit soft-delete overrides; don't assume the default fixture covers them.
- Page repeated related sort values with a unique parent-key tie-breaker. Assert exact totals and no repeated/missing IDs, and inspect query count to catch resource-triggered lazy loading.
- An unauthorized caller receives no rows; a second tenant cannot read a cached first-tenant author. A legitimate empty author name stays distinct from null.
- Inspect the production-driver plan. Search remaining package macros and use
composer why kirschbaum-development/eloquent-power-joinsbefore removing the dependency.
Run the app's listing, resource, pagination and authorization tests on its production database. Record versions, query counts, outputs and accepted differences with the change.
Sources
- MIT reference source:
src/Mixins/JoinRelationship.php,src/Mixins/RelationshipsExtraMethods.php,src/PowerJoinClause.php,tests/JoinWithGlobalScopeTest.php,tests/SoftDeletesTest.php, andtests/JoinRelationshipWithJoinTypesTest.php. - Framework source checked:
src/Illuminate/Database/Query/JoinClause.phpandQuery/Builder.php; reconcile the metadata with the application's lockfile. - Port options: check
get-recipe's current port catalog (sourced from Package Port) at implementation time.