Skip to content

Instantly share code, notes, and snippets.

@codemonkey76
Created December 7, 2022 00:48
Show Gist options
  • Save codemonkey76/2d21b6f6ddfb27c98cea57b22d63f8fa to your computer and use it in GitHub Desktop.
Save codemonkey76/2d21b6f6ddfb27c98cea57b22d63f8fa to your computer and use it in GitHub Desktop.
WithEdits Trait
<?php
namespace App\Http\Livewire\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
trait WithEdits
{
use WithAuthMessage;
public $showModal = false;
public Model $editing;
public abstract function getModelName(): string;
public abstract function emptyModel(): array;
public function bootWithEdits(): void
{
$this->editing = $this->getModelName()::make($this->emptyModel());
$this->listeners[] = 'showCreateModal';
$this->listeners[] = 'showEditModal';
$this->listeners[] = 'cancelEdit';
}
public function showCreateModal(array $params = []): bool
{
if (Gate::denies('create', $this->getModelName())) {
return $this->denied();
}
$this->editing = $this->getModelName()::make([...$this->emptyModel(), ...$params]);
if (method_exists($this, 'beforeCreate')) {
$this->beforeCreate();
}
$this->showModal = true;
return true;
}
public function showEditModal($modelId): bool
{
$model = $this->getModelName()::find($modelId);
if (Gate::denies('update', $model)) {
return $this->denied();
}
$this->editing = $model;
if (method_exists($this, 'beforeEdit')) {
$this->beforeEdit();
}
$this->showModal = true;
return true;
}
public function cancelEdit(): void
{
$this->editing = $this->getModelName()::make($this->emptyModel());
$this->showModal = false;
}
public function save(): bool
{
$isEditing = !!$this->editing->getKey();
if ($isEditing && Gate::denies('update', $this->editing)) return $this->denied();
if (!$isEditing && Gate::denies('create', $this->getModelName())) return $this->denied();
$this->validate();
$this->editing->save();
$this->cancelEdit();
$this->emit('refresh');
$strModel = Str::of($this->getModelName())->afterLast("\\");
$this->notify("$strModel saved successfully!");
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment