| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- <?php
- namespace App\Http\Livewire;
- use Livewire\Component;
- use Livewire\WithPagination;
- class City extends Component
- {
- use WithPagination;
- protected $paginationTheme = 'bootstrap';
- public $name, $enabled, $dataId, $province_id, $update = false, $add = false;
- public $provinces = array();
- protected $rules = [
- 'name' => 'required',
- 'province_id' => 'required'
- ];
- protected $messages = [
- 'name.required' => 'Il nome è obbligatorio'
- ];
- public function resetFields(){
- $this->name = '';
- $this->enabled = true;
- $this->province_id = null;
- }
- public function mount()
- {
- $this->provinces = \App\Models\Province::select('id', 'name')->get();
- }
- public function render()
- {
- $rows = \App\Models\City::with('province')->paginate(10);
- return view('livewire.city', ['records' => $rows]);
- }
- public function add()
- {
- $this->resetFields();
- $this->add = true;
- $this->update = false;
- }
- public function store()
- {
- $this->validate();
- try {
- \App\Models\City::create([
- 'name' => $this->name,
- 'province_id' => $this->province_id,
- 'enabled' => $this->enabled
- ]);
- session()->flash('success','Città creata');
- $this->resetFields();
- $this->add = false;
- } catch (\Exception $ex) {
- session()->flash('error','Errore (' . $ex->getMessage() . ')');
- }
- }
- public function edit($id){
- try {
- $city = \App\Models\City::findOrFail($id);
- if( !$city) {
- session()->flash('error','Città non trovata');
- } else {
- $this->name = $city->name;
- $this->enabled = $city->enabled;
- $this->province_id = $city->province_id;
- $this->dataId = $city->id;
- $this->update = true;
- $this->add = false;
- }
- } catch (\Exception $ex) {
- session()->flash('error','Errore (' . $ex->getMessage() . ')');
- }
- }
- public function update()
- {
- $this->validate();
- try {
- \App\Models\City::whereId($this->dataId)->update([
- 'name' => $this->name,
- 'province_id' => $this->province_id,
- 'enabled' => $this->enabled
- ]);
- session()->flash('success','Città aggiornata');
- $this->resetFields();
- $this->update = false;
- } catch (\Exception $ex) {
- session()->flash('error','Errore (' . $ex->getMessage() . ')');
- }
- }
- public function cancel()
- {
- $this->add = false;
- $this->update = false;
- $this->resetFields();
- }
- public function delete($id)
- {
- try{
- \App\Models\City::find($id)->delete();
- session()->flash('success',"Città eliminata");
- }catch(\Exception $e){
- session()->flash('error','Errore (' . $ex->getMessage() . ')');
- }
- }
- }
|