Nation.php 2.6 KB

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