1 | <?php |
||
10 | trait AppendsAttributesToResults |
||
11 | { |
||
12 | /** @var \Illuminate\Support\Collection */ |
||
13 | protected $allowedAppends; |
||
14 | |||
15 | public function allowedAppends($appends): self |
||
16 | { |
||
17 | $appends = is_array($appends) ? $appends : func_get_args(); |
||
18 | |||
19 | $this->allowedAppends = collect($appends); |
||
20 | |||
21 | $this->ensureAllAppendsExist(); |
||
22 | |||
23 | return $this; |
||
24 | } |
||
25 | |||
26 | protected function addAppendsToResults(Collection $results) |
||
27 | { |
||
28 | $appends = $this->request->appends(); |
||
|
|||
29 | return $results->each(function($item) use($appends) |
||
30 | { |
||
31 | $appends->each(function($append) use($item) |
||
32 | { |
||
33 | if(Str::contains($append, '.')) |
||
34 | { |
||
35 | $nestedAppends = collect(explode('.', $append)); |
||
36 | $relation = $nestedAppends->shift(); |
||
37 | |||
38 | $this->appendLoop($item, $relation, $nestedAppends); |
||
39 | } else |
||
40 | { |
||
41 | $item->append($append); |
||
42 | } |
||
43 | }); |
||
44 | }); |
||
45 | } |
||
46 | |||
47 | private function appendLoop($item, string $relation, Collection $nestedAppends) |
||
48 | { |
||
49 | if($item->relationLoaded($relation)) |
||
50 | { |
||
51 | if($nestedAppends->count() === 1) |
||
52 | { |
||
53 | $sub = $nestedAppends->first(); |
||
54 | if($item->$relation instanceof \Illuminate\Database\Eloquent\Collection) |
||
55 | { |
||
56 | $item->$relation->each(function($model) use($sub) |
||
57 | { |
||
58 | $model->append($sub); |
||
59 | }); |
||
60 | } else |
||
61 | { |
||
62 | $item->$relation->append($sub); |
||
63 | } |
||
64 | } else |
||
65 | { |
||
66 | $sub = $nestedAppends->shift(); |
||
67 | $this->appendLoop($item->$relation, $sub, $nestedAppends); |
||
68 | } |
||
69 | } |
||
70 | } |
||
71 | |||
72 | protected function ensureAllAppendsExist() |
||
82 | } |
||
83 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: