22
33namespace SkoreLabs \JsonApi \Http \Resources ;
44
5- use Illuminate \Database \Eloquent \Collection ;
5+ use Illuminate \Database \Eloquent \Collection as DatabaseCollection ;
66use Illuminate \Database \Eloquent \Model ;
7- use Illuminate \Database \Eloquent \Relations \Pivot ;
87use Illuminate \Support \Arr ;
8+ use Illuminate \Support \Collection ;
99
1010/**
1111 * @property mixed $resource
@@ -45,7 +45,7 @@ protected function attachRelations(Model $model)
4545 $ relations = array_filter ($ model ->getRelations ());
4646
4747 foreach ($ relations as $ relation => $ relationObj ) {
48- if ($ relationObj instanceof Collection ) {
48+ if ($ relationObj instanceof DatabaseCollection ) {
4949 /** @var \Illuminate\Database\Eloquent\Model $relationModel */
5050 foreach ($ relationObj ->all () as $ relationModel ) {
5151 $ this ->relationships [$ relation ]['data ' ][] = $ this ->processModelRelation (
@@ -54,7 +54,7 @@ protected function attachRelations(Model $model)
5454 }
5555 }
5656
57- if ($ relationObj instanceof Model && ! $ relationObj instanceof Pivot ) {
57+ if ($ relationObj instanceof Model) {
5858 $ this ->relationships [$ relation ]['data ' ] = $ this ->processModelRelation (
5959 $ relationObj
6060 );
@@ -72,10 +72,14 @@ protected function attachRelations(Model $model)
7272 protected function processModelRelation (Model $ model )
7373 {
7474 $ modelResource = new JsonApiResource ($ model , $ this ->authorize );
75+ $ modelIdentifier = $ modelResource ->getResourceIdentifier ();
7576
76- $ this ->addIncluded ($ modelResource );
77+ if (!empty (Arr::get ($ modelIdentifier , $ model ->getKeyName (), null ))) {
78+ $ this ->addIncluded ($ modelResource );
79+ return $ modelIdentifier ;
80+ }
7781
78- return $ modelResource -> getResourceIdentifier () ;
82+ return [] ;
7983 }
8084
8185 /**
@@ -93,9 +97,9 @@ protected function addIncluded(JsonApiResource $resource)
9397 array_values ($ resource ->getIncluded ()),
9498 ])->flatten ();
9599
96- Arr::set ($ this ->with , 'included ' , $ itemsCol -> unique ( static function ( $ resource ) {
97- return implode ( '' , $ resource -> getResourceIdentifier ());
98- } )->values ()->all ());
100+ Arr::set ($ this ->with , 'included ' , $ this -> checkUniqueness (
101+ $ itemsCol
102+ )->values ()->all ());
99103 }
100104
101105 /**
@@ -107,4 +111,18 @@ public function getIncluded()
107111 {
108112 return Arr::get ($ this ->with , 'included ' , []);
109113 }
114+
115+ /**
116+ * Check and return unique resources on a collection.
117+ *
118+ * @param \Illuminate\Support\Collection
119+ *
120+ * @return \Illuminate\Support\Collection
121+ */
122+ protected function checkUniqueness (Collection $ collection )
123+ {
124+ return $ collection ->unique (static function ($ resource ) {
125+ return implode ('' , $ resource ->getResourceIdentifier ());
126+ });
127+ }
110128}
0 commit comments