Skip to content

Commit

Permalink
Fixed HasMediaLibrary trait (resource creation was broken). Closes #33
Browse files Browse the repository at this point in the history
  • Loading branch information
toonvandenbos committed Aug 23, 2019
1 parent 2e22943 commit 23a0bf2
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/Concerns/HasMediaLibrary.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Whitecube\NovaFlexibleContent\Concerns;

use Whitecube\NovaFlexibleContent\Flexible;
use Spatie\MediaLibrary\MediaRepository;
use Spatie\MediaLibrary\HasMedia\HasMedia;
use Spatie\MediaLibrary\HasMedia\HasMediaTrait;
Expand All @@ -21,7 +22,13 @@ trait HasMediaLibrary {
*/
protected function getMediaModel() : HasMedia
{
return resolve(NovaRequest::class)->findModelOrFail();
$model = Flexible::getOriginModel();

if(is_null($model) || !($model instanceof HasMedia)) {
throw new \Exception('Origin HasMedia model not found.');
}

return $model;
}

/**
Expand Down
40 changes: 40 additions & 0 deletions src/Flexible.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ class Flexible extends Field
*/
protected static $validatedKeys = [];

/**
* All the validated attributes
*
* @var \Illuminate\Database\Eloquent\Model
*/
public static $model;

/**
* Create a fresh flexible field instance
*
Expand Down Expand Up @@ -212,6 +219,8 @@ public function resolve($resource, $attribute = null)
{
$attribute = $attribute ?? $this->attribute;

$this->registerModel($resource);

$this->buildGroups($resource, $attribute);

$this->value = $this->resolveGroups($this->groups);
Expand All @@ -232,6 +241,8 @@ protected function fillAttribute(NovaRequest $request, $requestAttribute, $model

$attribute = $attribute ?? $this->attribute;

$this->registerModel($model);

$this->buildGroups($model, $attribute);

$callbacks = collect($this->syncAndFillGroups($request, $requestAttribute));
Expand Down Expand Up @@ -493,4 +504,33 @@ public static function getValidationKey($key)
{
return static::$validatedKeys[$key] ?? null;
}

/**
* Registers a reference to the origin model for nested & contained fields
*
* @param mixed $model
* @return void
*/
protected function registerModel($model)
{
if(is_a($model, \Laravel\Nova\Resource::class)) {
$model = $model->model();
}

if(!is_a($model, \Illuminate\Database\Eloquent\Model::class)) {
return;
}

static::$model = $model;
}

/**
* Return the previously registered origin model
*
* @return null|\Illuminate\Database\Eloquent\Model
*/
public static function getOriginModel()
{
return static::$model;
}
}

0 comments on commit 23a0bf2

Please sign in to comment.