Card.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. namespace App\Http\Livewire;
  3. use Livewire\Component;
  4. class Card extends Component
  5. {
  6. public $records, $name, $enabled, $next_day_expire, $next_month_expire, $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->next_day_expire = null;
  16. $this->next_month_expire = null;
  17. $this->enabled = true;
  18. }
  19. public function render()
  20. {
  21. $this->records = \App\Models\Card::get();
  22. return view('livewire.card');
  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\Card::create([
  35. 'name' => $this->name,
  36. 'next_day_expire' => $this->next_day_expire,
  37. 'next_month_expire' => $this->next_month_expire,
  38. 'enabled' => $this->enabled
  39. ]);
  40. session()->flash('success','Tessera creata');
  41. $this->resetFields();
  42. $this->add = false;
  43. } catch (\Exception $ex) {
  44. session()->flash('error','Errore');
  45. }
  46. }
  47. public function edit($id){
  48. try {
  49. $card = \App\Models\Card::findOrFail($id);
  50. if( !$card) {
  51. session()->flash('error','Tessera non trovata');
  52. } else {
  53. $this->name = $card->name;
  54. $this->enabled = $card->enabled;
  55. $this->next_day_expire = $card->next_day_expire;
  56. $this->next_month_expire = $card->next_month_expire;
  57. $this->dataId = $card->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\Card::whereId($this->dataId)->update([
  70. 'name' => $this->name,
  71. 'next_day_expire' => $this->next_day_expire,
  72. 'next_month_expire' => $this->next_month_expire,
  73. 'enabled' => $this->enabled
  74. ]);
  75. session()->flash('success','Tessera 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\Card::find($id)->delete();
  92. session()->flash('success',"Tessera eliminata");
  93. }catch(\Exception $e){
  94. session()->flash('error',"Errore");
  95. }
  96. }
  97. }