Using PHP Traits for Laravel Eloquent Relationships

Tom Ellis
Tom Ellis
Sep 6, 2018 · 3 min read

I recently began refactoring a bunch of code on a project and found myself putting the same methods on my Eloquent models for a relation to an Account class. FYI I prefer to have getters and setters rather than accessing properties magically.

So lets say we have a Post model that looks something like this:

<?php

namespace
App;
use Illuminate\Database\Eloquent\Model;/**
* Class Post
*
*
@package App
*/
class Post extends Model
{
/**
*
@return string

Keep the story going. Sign up for an extra free read.

You've completed your member preview for this month, but when you sign up for a free Medium account, you get one more story.
Already have an account? Sign in

Tom Ellis

Written by

Tom Ellis

PHP and JavaScript hacker. Symfony and Laravel tinkerer. Creator of TomahawkPHP

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade