2
2
3
3
namespace SkoreLabs \JsonApi \Http \Resources ;
4
4
5
- use Illuminate \Database \Eloquent \Collection ;
5
+ use Illuminate \Database \Eloquent \Collection as DatabaseCollection ;
6
6
use Illuminate \Database \Eloquent \Model ;
7
- use Illuminate \Database \Eloquent \Relations \Pivot ;
8
7
use Illuminate \Support \Arr ;
8
+ use Illuminate \Support \Collection ;
9
9
10
10
/**
11
11
* @property mixed $resource
@@ -45,7 +45,7 @@ protected function attachRelations(Model $model)
45
45
$ relations = array_filter ($ model ->getRelations ());
46
46
47
47
foreach ($ relations as $ relation => $ relationObj ) {
48
- if ($ relationObj instanceof Collection ) {
48
+ if ($ relationObj instanceof DatabaseCollection ) {
49
49
/** @var \Illuminate\Database\Eloquent\Model $relationModel */
50
50
foreach ($ relationObj ->all () as $ relationModel ) {
51
51
$ this ->relationships [$ relation ]['data ' ][] = $ this ->processModelRelation (
@@ -54,7 +54,7 @@ protected function attachRelations(Model $model)
54
54
}
55
55
}
56
56
57
- if ($ relationObj instanceof Model && ! $ relationObj instanceof Pivot ) {
57
+ if ($ relationObj instanceof Model) {
58
58
$ this ->relationships [$ relation ]['data ' ] = $ this ->processModelRelation (
59
59
$ relationObj
60
60
);
@@ -72,10 +72,14 @@ protected function attachRelations(Model $model)
72
72
protected function processModelRelation (Model $ model )
73
73
{
74
74
$ modelResource = new JsonApiResource ($ model , $ this ->authorize );
75
+ $ modelIdentifier = $ modelResource ->getResourceIdentifier ();
75
76
76
- $ this ->addIncluded ($ modelResource );
77
+ if (!empty (Arr::get ($ modelIdentifier , $ model ->getKeyName (), null ))) {
78
+ $ this ->addIncluded ($ modelResource );
79
+ return $ modelIdentifier ;
80
+ }
77
81
78
- return $ modelResource -> getResourceIdentifier () ;
82
+ return [] ;
79
83
}
80
84
81
85
/**
@@ -93,9 +97,9 @@ protected function addIncluded(JsonApiResource $resource)
93
97
array_values ($ resource ->getIncluded ()),
94
98
])->flatten ();
95
99
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 ());
99
103
}
100
104
101
105
/**
@@ -107,4 +111,18 @@ public function getIncluded()
107
111
{
108
112
return Arr::get ($ this ->with , 'included ' , []);
109
113
}
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
+ }
110
128
}
0 commit comments