Replicate with relations #4544
-
|
I would like the ability to set the relations which should be replicated on replication. I have checked the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
|
I'm struggling with the same situation. I've been able to do it, but in my opinion quite an ugly hack. In my model, I've added a public property app/Models/MyModel.php <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
public ?int $_replicatedFrom = null;
//..
}So I can set the id in the resource replicate function. Note that I also have to add a hidden field for it. app/Nova/MyModel.php <?php
namespace App\Nova;
use Laravel\Nova\Fields\Hidden;
use Laravel\Nova\Http\Requests\NovaRequest;
class MyModel extends Resource
{
public function fields(NovaRequest $request): array
{
return [
//..
Hidden::('Replicated', '_replicatedFrom')
];
}
public function replicate(): Resource
{
$originalId = $this->model()?->id;
return tap(parent::replicate(), function(Resource $resource) use ($originalId) {
$model = $resource->model();
$model->_replicatedFrom = $originalId;
});
}
}With this, in a ModelObserver on the created event, you can check if this value is set and apply the replications for relationships if you like: app/Observers/MyModelObserver.php <?php
namespace App\Observers;
use App\Models\MyModel;
class MyModelObserver
{
public function created(MyModel $model): void
{
if($model->_replicatedFrom) {
// perform replicating of relations
}
}
}To me this is very ugly, but I haven't found a better solution so far. |
Beta Was this translation helpful? Give feedback.
-
|
On the latest version you should be able to do the following: namespace App\Observers;
use App\Models\Post;
use Laravel\Nova\Http\Requests\NovaRequest;
use Laravel\Nova\Nova;
class PostObserver
{
public function creating(Post $model): void
{
Nova::whenServing(function (NovaRequest $request) use ($model) {
$model->parent_id = $request->input('fromResourceId');
});
}
} |
Beta Was this translation helpful? Give feedback.
On the latest version you should be able to do the following: