Adding app/Http/Livewire/Form/ModelForm.php
This commit is contained in:
parent
9f147821b3
commit
5f960cf3d9
1 changed files with 76 additions and 0 deletions
76
app/Http/Livewire/Form/ModelForm.php
Normal file
76
app/Http/Livewire/Form/ModelForm.php
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
<?php
|
||||
|
||||
namespace App\Http\Livewire\Form;
|
||||
|
||||
use App\Http\Livewire\Traits\Alert;
|
||||
|
||||
use Livewire\Component;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
abstract class ModelForm extends Component
|
||||
{
|
||||
use Alert;
|
||||
|
||||
/**
|
||||
* The model record
|
||||
*/
|
||||
public $record;
|
||||
|
||||
/**
|
||||
* True if the record already exists in the database.
|
||||
*/
|
||||
public bool $exist;
|
||||
|
||||
/**
|
||||
* Redirect after this route after record was created.
|
||||
*/
|
||||
public string $redirect_route;
|
||||
|
||||
/**
|
||||
* Get the name of the model
|
||||
*/
|
||||
public function getModelName() : string
|
||||
{
|
||||
return Str::afterLast(get_class($this->record), '\\');
|
||||
}
|
||||
|
||||
public function updated($property, $value)
|
||||
{
|
||||
$this->validateOnly($property);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if this record has not been stored in the database.
|
||||
*/
|
||||
public function isNew() : bool
|
||||
{
|
||||
return !$this->exist;
|
||||
}
|
||||
|
||||
/**
|
||||
* Submit the form, create/update record.
|
||||
*/
|
||||
public function submit()
|
||||
{
|
||||
$this->validate();
|
||||
$this->record->save();
|
||||
|
||||
if ($this->isNew()) {
|
||||
session()->flash('info', "{$this->getModelName()} was successfully created.");
|
||||
return redirect()->route($this->redirect_route);
|
||||
}
|
||||
|
||||
$this->info("{$this->getModelName()} was successfully updated.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the setup page
|
||||
*/
|
||||
public function render()
|
||||
{
|
||||
$script = Str::lower($this->getModelName());
|
||||
|
||||
return view("form.$script")
|
||||
->layout('layouts.admin');
|
||||
}
|
||||
}
|
||||
Reference in a new issue