Category.php 2.8 KB

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