-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
cf94b16
commit 6a2b6d1
Showing
3 changed files
with
136 additions
and
68 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
<?php | ||
|
||
namespace Armincms\Fields; | ||
|
||
use Laravel\Nova\Fields\Select; | ||
|
||
class MorphToMany extends BelongsToMany | ||
{ | ||
/** | ||
* Create a new field. | ||
* | ||
* @param string $name | ||
* @param string|null $attribute | ||
* @param string|null $resource | ||
* @return void | ||
*/ | ||
public function __construct($name, $attribute = null, $resource = null) | ||
{ | ||
parent::__construct($name, $attribute, $resource); | ||
|
||
$this->pivots(); | ||
$this->fields(function() {}); | ||
} | ||
|
||
/** | ||
* Specify the callback to be executed to retrieve the pivot fields. | ||
* | ||
* @param callable $callback | ||
* @return $this | ||
*/ | ||
public function fields(callable $callback) | ||
{ | ||
$this->fieldsCallback = function($request, $resource) use ($callback) { | ||
$relation = $this->getMorphToMany($resource); | ||
|
||
return collect(call_user_func($callback, $request, $resource))->prepend( | ||
Select::make(__("Resource"), $relation->getMorphType($resource)) | ||
->options([ | ||
$relation->getMorphClass() => $resource::label(), | ||
]) | ||
->onlyOnForms() | ||
->required() | ||
->rules('required') | ||
->withMeta(['value' => $relation->getMorphClass()]) | ||
)->all(); | ||
}; | ||
|
||
return $this; | ||
} | ||
|
||
/** | ||
* Indicated the MorphToMany relationship. | ||
* | ||
* @return \Illuminate\Database\Eloquent\Relations\MorphToMany | ||
*/ | ||
protected function getMorphToMany($resource) | ||
{ | ||
$model = $resource::newModel(); | ||
|
||
return $model->{$this->manyToManyRelationship}(); | ||
} | ||
|
||
/** | ||
* Set the pivots attachment status. | ||
* | ||
* @return string | ||
*/ | ||
public function pivots(bool $pivots = true) | ||
{ | ||
$this->pivots = true; | ||
|
||
return $this; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters