-
Notifications
You must be signed in to change notification settings - Fork 106
/
AttachController.php
84 lines (70 loc) · 2.8 KB
/
AttachController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
namespace NovaAttachMany\Http\Controllers;
use Illuminate\Support\Str;
use Illuminate\Routing\Controller;
use Laravel\Nova\Http\Requests\NovaRequest;
class AttachController extends Controller
{
public function create(NovaRequest $request, $parent, $relationship)
{
return [
'available' => $this->getAvailableResources($request, $relationship),
];
}
public function edit(NovaRequest $request, $parent, $parentId, $relationship)
{
$foundResource = $request->findResourceOrFail();
if(! method_exists($foundResource->model(), $relationship)) {
abort(500, class_basename($foundResource->model()) . " is missing relationship: $relationship");
}
$keyName = $foundResource->model()->{$relationship}()->getModel()->getKeyName();
return [
'selected' => $foundResource->model()->{$relationship}->pluck($keyName),
'available' => $this->getAvailableResources($request, $relationship),
];
}
public function getAvailableResources($request, $relationship)
{
$resourceClass = $request->newResource();
$field = $resourceClass
->availableFields($request)
->where('component', 'nova-attach-many')
->where('attribute', $relationship)
->first();
$query = $field->resourceClass::newModel();
return forward_static_call($this->associatableQueryCallable($request, $query), $request, $query, $field)->get()
->mapInto($field->resourceClass)
->filter(function ($resource) use ($request, $field) {
return $request->newResource()->authorizedToAttach($request, $resource->resource);
})->map(function ($resource) use ($request, $field) {
return $field->formatAssociatableResource($request, $resource);
})->values();
}
/**
* Get the associatable query method name.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param \Illuminate\Database\Eloquent\Model $model
* @return array
*/
protected function associatableQueryCallable(NovaRequest $request, $model)
{
return ($method = $this->associatableQueryMethod($request, $model))
? [$request->resource(), $method]
: [$request->newResource(), 'relatableQuery'];
}
/**
* Get the associatable query method name.
*
* @param \Laravel\Nova\Http\Requests\NovaRequest $request
* @param \Illuminate\Database\Eloquent\Model $model
* @return string
*/
protected function associatableQueryMethod(NovaRequest $request, $model)
{
$method = 'relatable'.Str::plural(class_basename($model));
if (method_exists($request->resource(), $method)) {
return $method;
}
}
}