Skip to content

Commit 29f78da

Browse files
committed
Add support for nested relationship serialisation
1 parent 1607234 commit 29f78da

File tree

2 files changed

+40
-5
lines changed

2 files changed

+40
-5
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?php
2+
3+
namespace Huntie\JsonApi\Exceptions;
4+
5+
use Exception;
6+
7+
class InvalidRelationPathException extends Exeption
8+
{
9+
/**
10+
* Create a new InvalidRelationPathException instance.
11+
*
12+
* @param string $path The relation path attempted
13+
* @param int|null $code User defined exception code
14+
* @param Exception|null $previous Previous exception if nested
15+
*/
16+
public function __construct($path, $code = 0, Exception $previous = null)
17+
{
18+
$message = sprintf('The relationship path "%s" could not be resolved', $path);
19+
20+
parent::__construct($message, $code, $previous);
21+
}
22+
}

src/Serializers/RelationshipSerializer.php

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Huntie\JsonApi\Serializers;
44

5+
use Exception;
6+
use Huntie\JsonApi\Exceptions\InvalidRelationPathException;
57
use Illuminate\Database\Eloquent\Model;
68
use Illuminate\Support\Collection;
79

@@ -24,15 +26,26 @@ class RelationshipSerializer extends JsonApiSerializer
2426
/**
2527
* Create a new JSON API relationship serializer.
2628
*
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
3034
*/
31-
public function __construct($record, $relation, array $fields = [])
35+
public function __construct($record, $path, array $fields = [])
3236
{
3337
parent::__construct();
3438

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+
3649
$this->fields = array_unique($fields);
3750
}
3851

0 commit comments

Comments
 (0)