Using traits with livewire

Viewed 635

I'm building livewire components that shares 50% of public properties and almost 90% of submit function logic.

each component using this trait has its own rules according to its html-form fields. and also each component perform some custom logic after validating the data. other that that they are all the same.

<?php

namespace App\Traits;

 trait ParentServiceComponent
 {

   public $desc = '';

   public function rules()
   {
      return [
          'desc' => 'required|max:2000'
      ];
   }

  public abstract function componentCustomLogic(array $data);

  public function submit()
  {
    $data = $this->validate();
    
    $performCusomLogic = $this->componentCustomLogic($data);
    
    // save to db and show success message
  } 
}

here an example of two components that uses this trait.

<?php

namespace App\Http\Livewire;

use Livewire\Component;

use App\Traits\ParentServiceComponent;

class RequestService extends Component
{

    public $type = '';

    use ParentServiceComponent { rules as traitRules; }

    public function rules()
    {
        return array_merge($this->traitRules, [
            'type' => 'required|max:200'
        ]);
    }

    public function componentCustomLogic(array $data)
    {
        // do the logic of this component here
    }

    public function render()
    {
        return view('livewire.request-service');
    }
}

<?php

namespace App\Http\Livewire;

use Livewire\Component;

use App\Traits\ParentServiceComponent;

class ReplyService extends Component
{

    public $body = '';

    use ParentServiceComponent { rules as traitRules; }

    public function rules()
    {
        return array_merge($this->traitRules, [
            'body' => 'required|max:200'
        ]);
    }

    public function componentCustomLogic(array $data)
    {
        // do the logic of this component here
    }

    public function render()
    {
        return view('livewire.reply-service');
    }
}

so my question is: am I doing it right?

0 Answers
Related