Search code examples
laravelmodelhelper

Laravel 8: How to use helper class in model


I think this seems clumsy. How do you suggest I use a helper class in my model when setting an attribute?

I want to avoid using static methods.

use App\Helpers\Tools;

class Customer extends Model
{
    public function setPhoneAttribute(string $value): void
    {
        $this->attributes['phone'] = (new Tools)->clean($value);
    }
}

This doesn't seemd to work:

use App\Helpers\Tools;

class Customer extends Model
{
    public function setPhoneAttribute(Tools $tools, string $value): void
    {
        $this->attributes['phone'] = $tools->clean($value);
    }
}

Solution

  • this way should be working without errors:

    use App\Helpers\Tools;
    
    class Customer extends Model
    {
        public function setPhoneAttribute(string $value): void
        {
            $this->attributes['phone'] = (new Tools)->clean($value);
        }
    }
    

    the other code snippet is incorrect, set{Column}Attribute will only pass the $value argument.

    you can create your own helper function or Facade to help you control the actual class/function performing the clean from one place.