1
0
Fork 0
wow-raid-bingo/app/Http/Livewire/Form/CardForm.php

104 lines
1.9 KiB
PHP

<?php
namespace App\Http\Livewire\Form;
use App\Models\Card;
use App\Models\Character;
use App\Models\Raid;
use App\Models\Wow;
use App\Http\Livewire\Traits\Alert;
use Livewire\Component;
class CardForm extends Component
{
use Alert;
/**
* The card record
*/
public $card;
/**
* Array of available characters
*/
public $characters;
/**
* Array of available raids
*/
public $raids;
/**
* True if the record already exists in the database.
*/
public bool $exist;
public function mount(Card $card)
{
$this->card = $card;
$this->characters = Character::all()->pluck('name', 'id');
$this->raids = Raid::all()->pluck('name', 'id');
$this->classes = Wow::$classes;
$this->exist = $card->exists;
}
/**
* Validation rules
*/
protected function rules()
{
return [
'card.body' => 'required|string|min:3|max:200',
'card.character_id' => 'exists:' . Character::class . ',id|nullable',
'card.raid_id' => 'exists:' . Raid::class . ',id|nullable',
'card.class' => 'in:' . collect($this->classes)->keys() . '|nullable',
];
}
public function updated($property, $value)
{
// Hack to force empty value to null.
if (in_array($property, ['card.character_id', 'card.raid_id', 'card.class'])) {
if (empty($value)) {
$this->{$property} = null;
}
}
$this->validateOnly($property);
}
/**
* Returns true if this card has not been stored in the database.
*/
public function isNew() : bool
{
return !$this->exist;
}
/**
* Submit the form, create/update card.
*/
public function submit()
{
$this->validate();
$this->card->save();
if ($this->isNew()) {
session()->flash('info', 'Card was successfully created.');
return redirect()->route('admin.card.index');
}
$this->info('Card was successfully updated.');
}
/**
* Render the setup page
*/
public function render()
{
return view('form.card')
->layout('layouts.admin');
}
}