Nation.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. class Nation extends Component
  5. {
  6. public $records, $code, $name, $enabled, $isItaly, $dataId, $update = false, $add = false;
  7. protected $rules = [
  8. 'name' => 'required'
  9. ];
  10. protected $messages = [
  11. 'name.required' => 'Il nome è obbligatorio'
  12. ];
  13. public function resetFields(){
  14. $this->name = '';
  15. $this->code = '';
  16. $this->enabled = true;
  17. $this->isItaly = false;
  18. }
  19. public function render()
  20. {
  21. $this->records = \App\Models\Nation::select('id', 'name', 'code', 'enabled')->get();
  22. return view('livewire.nation');
  23. }
  24. public function add()
  25. {
  26. $this->resetFields();
  27. $this->add = true;
  28. $this->update = false;
  29. }
  30. public function store()
  31. {
  32. $this->validate();
  33. try {
  34. \App\Models\Nation::create([
  35. 'name' => $this->name,
  36. 'code' => $this->code,
  37. //'enabled' => $this->enabled,
  38. //'is_italy' => $this->isItaly,
  39. ]);
  40. session()->flash('success','Nazione creata');
  41. $this->resetFields();
  42. $this->add = false;
  43. } catch (\Exception $ex) {
  44. session()->flash('error','Errore in fase di salvataggio');
  45. }
  46. }
  47. public function edit($id){
  48. try {
  49. $nation = \App\Models\Nation::findOrFail($id);
  50. if( !$nation) {
  51. session()->flash('error','Nazione non trovata');
  52. } else {
  53. $this->name = $nation->name;
  54. $this->code = $nation->code;
  55. $this->enabled = $nation->enabled;
  56. $this->isItaly = $nation->is_italy;
  57. $this->dataId = $nation->id;
  58. $this->update = true;
  59. $this->add = false;
  60. }
  61. } catch (\Exception $ex) {
  62. session()->flash('error','Errore');
  63. }
  64. }
  65. public function update()
  66. {
  67. $this->validate();
  68. try {
  69. \App\Models\Nation::whereId($this->dataId)->update([
  70. 'name' => $this->name,
  71. 'code' => $this->code,
  72. 'enabled' => $this->enabled,
  73. 'is_italy' => $this->isItaly,
  74. ]);
  75. session()->flash('success','Nazione aggiornata');
  76. $this->resetFields();
  77. $this->update = false;
  78. } catch (\Exception $ex) {
  79. session()->flash('success','Errore');
  80. }
  81. }
  82. public function cancel()
  83. {
  84. $this->add = false;
  85. $this->update = false;
  86. $this->resetFields();
  87. }
  88. public function delete($id)
  89. {
  90. try{
  91. \App\Models\Nation::find($id)->delete();
  92. session()->flash('success',"Nazione eliminata");
  93. }catch(\Exception $e){
  94. session()->flash('error',"Errore");
  95. }
  96. }
  97. }