2
2
3
3
namespace Huntie \JsonApi \Serializers ;
4
4
5
+ use Exception ;
6
+ use Huntie \JsonApi \Exceptions \InvalidRelationPathException ;
5
7
use Illuminate \Database \Eloquent \Model ;
6
8
use Illuminate \Support \Collection ;
7
9
@@ -24,15 +26,26 @@ class RelationshipSerializer extends JsonApiSerializer
24
26
/**
25
27
* Create a new JSON API relationship serializer.
26
28
*
27
- * @param Model $record The primary record
28
- * @param string $relation The named relation to serialize
29
- * @param array|null $fields Subset of fields to return by record type
29
+ * @param Model $record The primary record
30
+ * @param string $path The path to the relation to serialize
31
+ * @param array|null $fields Subset of fields to return by record type
32
+ *
33
+ * @throws InvalidRelationPathException
30
34
*/
31
- public function __construct ($ record , $ relation , array $ fields = [])
35
+ public function __construct ($ record , $ path , array $ fields = [])
32
36
{
33
37
parent ::__construct ();
34
38
35
- $ this ->relation = $ record ->{$ relation };
39
+ try {
40
+ $ this ->relation = $ record ;
41
+
42
+ foreach (explode ('. ' , $ path ) as $ relation ) {
43
+ $ this ->relation = $ this ->relation ->{$ relation };
44
+ }
45
+ } catch (Exception $ e ) {
46
+ throw new InvalidRelationPathException ($ path );
47
+ }
48
+
36
49
$ this ->fields = array_unique ($ fields );
37
50
}
38
51
0 commit comments