Traits in PHP are a way to reuse code. And that means you can use traits with the Laravel framework. This is not a tutorial as such, more a description of how I used traits to solve a problem.

First, get this from the PHP docs:

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait reduces some limitations of single inheritance. They enable a developer to reuse sets of methods in independent classes. Classes that are in different class hierarchies.

Yep, that’s it. I should stop writing now.

What does that mean in reality, though?

A problem

I used to use the CodeIgniter framework. I can hear you booing and hissing…

One of the things I liked about the framework was this: it was easy to add common functionality. You could create helpers or libraries. Load ’em up where you needed the functionality and off you went.

Laravel has a more modern way of offering a solution. And I bet you are not shocked to know I’m talking about traits.

So, my problem was this. See those Haiku poems over on the right of this page? I wanted to include them throughout this site. And I wanted a way to share the code that selects one at random.

A solution

I’m not suggesting the way I went about it is the only way. I’m saying it is one way to fix the problem.

  1. Create a trait folder in the app directory called traits.
  2. Create a new class in this folder and name it ( I called mine ‘TheHaikus’).

In your class, namespace it:


Then, make your class:

trait YourClassName
    public function someFunction()
        //code here

Then you are ready to use your trait.

Putting it to work

Here’s the sharing part. You have a controller that you would like to call a trait class method in to.

So, you use the trait:

use App\Traits\YourClassName;

And in the class body, specify the trait once more:

class SomeController extends Controller
    use YourClassName;

    public function whatever()
         //we can use the class now
          $foo = $this->someMethodFromMyTrait();

And away you go. Job done.

Notes and after-thoughts

This feels to me like a convenient way to add more functionality to your web build. And add it in a neat, structured way.

It does feel like sharing code in a proper sense – with little overhead.

Here’s another cool thing: you have access to all the usual stuff from the framework in your trait. You can get stuff from your database for example.

Traits are easy to use in Laravel. Give ’em a go when you have a real need to share some code – you won’t regret it.