Laravel: Creating a common function for all models

Viewed 2148

In my laravel(7.x) application, I have a common functionality to show the count of all the active and inactive records in all the modules. Therefore, I am obligated to repeat the same functionality on every module.

For example: Device, DeviceType, DeviceCompany, etc models have a same method called _getTotal and everywhere that _getTotal method is doing the same work.

Device.php

class Device extends Model
{
    protected $table = 'devices';

    ...

    public function _getTotal($status = \Common::STATUS_ACTIVE)
    {
        return self::where([
            'status' => $status
        ])->count() ?? 0;
    }
}

DeviceType.php

class DeviceType extends Model
{
    protected $table = 'device_types';

    ...

    public function _getTotal($status = \Common::STATUS_ACTIVE)
    {
        return self::where([
            'status' => $status
        ])->count() ?? 0;
    }
}

I tried to put this method in the Base Model but I think may not be a good practice. Am I right..?
Is there any way to make this method _getTotal a common method for all the modules..?

3 Answers

You could move this method to a trait and include the trait instead to all classes that need this method.

trait DeviceStatusTotal
{
    public function _getTotal($status = \Common::STATUS_ACTIVE)
    {
        return self::where([
            'status' => $status
        ])->count() ?? 0;
    }
}

DeviceType.php

class DeviceType extends Model
{
    use DeviceStatusTotal;

    protected $table = 'device_types';

    // ...
}

Or you can create a classe extending Model default class and your models extends from this custom class (that haves your custom function)

Related