JaredDev Logo

Laravel Model Helpers Using Traits

2017-09-13

I've become a fan of keeping my Laravel models "pure". By that I simply mean that they don't contain anything beyond the code for mutators, assessors, and the relationship definitions.

I don't want people to take this as chastising another dev for working with their models in a different way...this is just what I've started to become a fan of!

Previously Used Syntax

/* Invoice.php */
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Traits\InvoiceTrait;

class Invoice extends Model
{
    use InvoiceTrait;

    public function lineItemTotal() {
        /**
         * Code to total LineItems
         */
    }

    /**
     * Relationships
     */

    public function line_items()
    {
        return $this->hasMany(LineItem::class);
    }
}

Current Used Syntax

/* Invoice.php */
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Traits\InvoiceTrait;

class Invoice extends Model
{
    use InvoiceTrait;

    /**
     * Relationships
     */

    public function line_items()
    {
        return $this->hasMany(LineItem::class);
    }
}

/* InvoiceTrait.php */
<?php
namespace App\Traits;

use App\Models\Invoice;

trait InvoiceTrait {
    public function __toString() {
        // Return your default property or combination of them
    }

    public function lineItemTotal() {
        /**
         * Code to total LineItems
         */
    }

}

While coding using this method does put your code in two separate places it allows you to keep some segregation in your code.