2323use Illuminate \Contracts \Validation \Validator ;
2424use Illuminate \Database \Eloquent \Model ;
2525use Illuminate \Http \Response ;
26+ use Illuminate \Support \Collection ;
2627use LaravelJsonApi \Contracts \Auth \Authorizer ;
2728use LaravelJsonApi \Contracts \Schema \Relation ;
2829use LaravelJsonApi \Core \Document \ResourceObject ;
2930use LaravelJsonApi \Core \Exceptions \JsonApiException ;
3031use LaravelJsonApi \Core \Query \IncludePaths ;
32+ use LaravelJsonApi \Core \Store \LazyRelation ;
3133use LaravelJsonApi \Core \Support \Str ;
3234use LaravelJsonApi \Spec \RelationBuilder ;
3335use LaravelJsonApi \Spec \ResourceBuilder ;
@@ -49,6 +51,11 @@ class ResourceRequest extends FormRequest
4951 */
5052 private ?array $ validationData = null ;
5153
54+ /**
55+ * @var LazyRelation|null
56+ */
57+ private ?LazyRelation $ relation = null ;
58+
5259 /**
5360 * Specify the callback to use to guess the request class for a JSON API resource.
5461 *
@@ -116,6 +123,38 @@ public function modelOrFail(): object
116123 throw new LogicException ('No model exists for this route. ' );
117124 }
118125
126+ /**
127+ * Get the model referenced in a to-one relationship.
128+ *
129+ * @return Model|object|null
130+ */
131+ public function toOne (): ?object
132+ {
133+ if ($ this ->isModifyingRelationship ()) {
134+ return $ this ->relation ()->get ();
135+ }
136+
137+ throw new LogicException (
138+ 'Can only retrieve the model for a to-one relationship when the relationship is being modified. '
139+ );
140+ }
141+
142+ /**
143+ * Get the models referenced in a to-many relationship.
144+ *
145+ * @return Collection
146+ */
147+ public function toMany (): Collection
148+ {
149+ if ($ this ->isModifyingRelationship ()) {
150+ return $ this ->relation ()->collect ();
151+ }
152+
153+ throw new LogicException (
154+ 'Can only retrieve the models for a to-many relationship when the relationship is being modified. '
155+ );
156+ }
157+
119158 /**
120159 * Perform resource authorization.
121160 *
@@ -557,4 +596,22 @@ private function validateRelationshipDocument(): void
557596 }
558597 }
559598
599+ /**
600+ * @return LazyRelation
601+ */
602+ private function relation (): LazyRelation
603+ {
604+ if ($ this ->relation ) {
605+ return $ this ->relation ;
606+ }
607+
608+ $ jsonApi = $ this ->jsonApi ();
609+
610+ return $ this ->relation = new LazyRelation (
611+ $ jsonApi ->server (),
612+ $ jsonApi ->route ()->relation (),
613+ $ this ->json ()->all (),
614+ );
615+ }
616+
560617}
0 commit comments