|
5 | 5 | use Illuminate\Database\Eloquent\Model;
|
6 | 6 | use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
7 | 7 | use Illuminate\Database\Eloquent\Relations\HasOne;
|
| 8 | +use Illuminate\Database\Eloquent\Relations\MorphMany; |
8 | 9 | use Illuminate\Database\Eloquent\Relations\MorphOne;
|
9 | 10 | use Illuminate\Database\Eloquent\Relations\MorphTo;
|
| 11 | +use Illuminate\Database\Eloquent\Relations\MorphToMany; |
10 | 12 | use Illuminate\Database\Eloquent\Relations\Relation;
|
11 | 13 | use Illuminate\Support\Arr;
|
12 | 14 | use Illuminate\Support\Collection;
|
@@ -79,6 +81,37 @@ public function requestedRelations(Request $request): array
|
79 | 81 | return $validatedIncludes;
|
80 | 82 | }
|
81 | 83 |
|
| 84 | + public function relationInstanceFromParamConstraint(string $resourceModelClass, string $paramConstraint): Relation |
| 85 | + { |
| 86 | + $resourceModel = new $resourceModelClass(); |
| 87 | + |
| 88 | + do { |
| 89 | + $relationName = $this->rootRelationFromParamConstraint($paramConstraint); |
| 90 | + $paramConstraint = str_replace("{$relationName}.", '', $paramConstraint); |
| 91 | + |
| 92 | + $relation = $resourceModel->{$relationName}(); |
| 93 | + |
| 94 | + if (in_array(get_class($relation), [MorphTo::class, MorphMany::class, MorphToMany::class, MorphOne::class])) { |
| 95 | + break; |
| 96 | + } |
| 97 | + |
| 98 | + $resourceModel = $relation->getModel(); |
| 99 | + } while (str_contains($paramConstraint, '.')); |
| 100 | + |
| 101 | + return $relation; |
| 102 | + } |
| 103 | + |
| 104 | + /** |
| 105 | + * Resolves relation name from the given param constraint. |
| 106 | + * |
| 107 | + * @param string $paramConstraint |
| 108 | + * @return string |
| 109 | + */ |
| 110 | + public function rootRelationFromParamConstraint(string $paramConstraint): string |
| 111 | + { |
| 112 | + return Arr::first(explode('.', $paramConstraint)); |
| 113 | + } |
| 114 | + |
82 | 115 | /**
|
83 | 116 | * Resolves relation name from the given param constraint.
|
84 | 117 | *
|
@@ -139,7 +172,7 @@ public function relationForeignKeyFromRelationInstance(Relation $relationInstanc
|
139 | 172 | */
|
140 | 173 | public function getQualifiedRelationFieldName(Relation $relation, string $field): string
|
141 | 174 | {
|
142 |
| - if ($relation instanceof MorphTo) { |
| 175 | + if (in_array(get_class($relation), [MorphTo::class, MorphMany::class, MorphToMany::class, MorphOne::class])) { |
143 | 176 | return $field;
|
144 | 177 | }
|
145 | 178 |
|
|
0 commit comments