| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace App\Http\Livewire;
- use Livewire\Component;
- class Category extends Component
- {
- public $categories, $parentId, $name, $enabled, $categoryId, $updateCategory = false, $addCategory = false;
- protected $listeners = [
- 'deleteCategoryListner'=>'deleteCategory'
- ];
- protected $rules = [
- 'name' => 'required'
- ];
- public function resetFields(){
- $this->name = '';
- $this->enabled = true;
- }
- public function render()
- {
- $this->categories = Category::select('id', 'name', 'enabled')->get();
- return view('livewire.category');
- }
- public function addCategory()
- {
- $this->resetFields();
- $this->addCategory = true;
- $this->updateCategory = false;
- }
- public function storeCategory()
- {
- $this->validate();
- try {
- Category::create([
- 'name' => $this->name,
- 'parent' => $this->$parentId,
- 'enabled' => $this->enabled
- ]);
- session()->flash('success','Categoria creata');
- $this->resetFields();
- $this->addCategory = false;
- } catch (\Exception $ex) {
- session()->flash('error','Errore in fase di salvataggio');
- }
- }
- public function editCategory($id){
- try {
- $category = Category::findOrFail($id);
- if( !$category) {
- session()->flash('error','Categoria non trovata');
- } else {
- $this->name = $category->name;
- $this->enabled = $category->enabled;
- $this->parentId = $category->parent_id;
- $this->categoryId = $category->id;
- $this->updateCategory = true;
- $this->addCategory = false;
- }
- } catch (\Exception $ex) {
- session()->flash('error','Errore');
- }
- }
- public function updateCategory()
- {
- $this->validate();
- try {
- Category::whereId($this->categoryId)->update([
- 'name' => $this->name,
- 'parent' => $this->$parentId,
- 'enabled' => $this->enabled
- ]);
- session()->flash('success','Categoria aggiornata');
- $this->resetFields();
- $this->updateCategory = false;
- } catch (\Exception $ex) {
- session()->flash('success','Errore');
- }
- }
- public function cancelCategory()
- {
- $this->addCategory = false;
- $this->updateCategory = false;
- $this->resetFields();
- }
- public function deleteCategory($id)
- {
- try{
- Category::find($id)->delete();
- session()->flash('success',"Categoria eliminata");
- }catch(\Exception $e){
- session()->flash('error',"Errore");
- }
- }
- }
|