Province.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. class Province extends Component
  5. {
  6. public $provinces, $name, $enabled, $provinceId, $nationId, $updateProvince = false, $addProvince = false;
  7. protected $listeners = [
  8. 'deleteProvinceListner'=>'deleteProvince'
  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->provinces = Province::select('id', 'name', 'enabled')->get();
  20. return view('livewire.province');
  21. }
  22. public function addProvince()
  23. {
  24. $this->resetFields();
  25. $this->addProvince = true;
  26. $this->updateProvince = false;
  27. }
  28. public function storeProvince()
  29. {
  30. $this->validate();
  31. try {
  32. Province::create([
  33. 'name' => $this->name,
  34. 'nation_id' => $this->nationId,
  35. 'enabled' => $this->enabled
  36. ]);
  37. session()->flash('success','Provincia creata');
  38. $this->resetFields();
  39. $this->addProvince = false;
  40. } catch (\Exception $ex) {
  41. session()->flash('error','Errore in fase di salvataggio');
  42. }
  43. }
  44. public function editProvince($id){
  45. try {
  46. $province = Province::findOrFail($id);
  47. if( !$province) {
  48. session()->flash('error','Provincia non trovata');
  49. } else {
  50. $this->name = $province->name;
  51. $this->enabled = $province->enabled;
  52. $this->nationId = $province->nationId;
  53. $this->provinceId = $province->id;
  54. $this->updateProvince = true;
  55. $this->addProvince = false;
  56. }
  57. } catch (\Exception $ex) {
  58. session()->flash('error','Errore');
  59. }
  60. }
  61. public function updateProvince()
  62. {
  63. $this->validate();
  64. try {
  65. Province::whereId($this->provinceId)->update([
  66. 'name' => $this->name,
  67. 'nation_id' => $this->nationId,
  68. 'enabled' => $this->enabled
  69. ]);
  70. session()->flash('success','Provincia aggiornata');
  71. $this->resetFields();
  72. $this->updateProvince = false;
  73. } catch (\Exception $ex) {
  74. session()->flash('success','Errore');
  75. }
  76. }
  77. public function cancelProvince()
  78. {
  79. $this->addProvince = false;
  80. $this->updateProvince = false;
  81. $this->resetFields();
  82. }
  83. public function deleteProvince($id)
  84. {
  85. try{
  86. Province::find($id)->delete();
  87. session()->flash('success',"Provincia eliminata");
  88. }catch(\Exception $e){
  89. session()->flash('error',"Errore");
  90. }
  91. }
  92. }