Lawson  Wehner

Lawson Wehner


How to Use and Test Traits in Laravel

PHP Traits are a fantastic tool for sharing common functionality throughout your PHP classes. At first, this may seem a little intimidating. But, we’ll be up and running in no time with a couple of examples.

When Should We Use Traits?

Before we dive into the examples, let’s take a moment to discuss when we’d use a Trait. A lot of the time, we’ll end up using a Trait when we add in a package. Utilizing a Trait from a package is a standard pattern because it allows package writers to encapsulate useful functionality that we can add to our classes on an as-needed basis.

An excellent example of this is the Spatie  laravel-permission package. By adding their HasRoles Trait to our classes, we can then use the Trait’s functionality to manage roles.

Additionally, the Laravel framework itself uses Traits to layer functionality and complexity when needed. Notable examples that you might run across include AuthenticatesUsers and Notifiable.

Lastly, while it’s great to use Traits provided by others, when should we make one ourselves? Typically, it’s a good idea to make one if we find ourselves repeating a lot of functionality across many classes. For example, we could make a Uuidable Trait if a lot of our models are using a UUID.

A less common use-case is to use Traits to break up a God class. But for the most part, there are better ways to do this and Traits aren’t recommended unless you’re going to be sharing the extracted functionality with many other classes.

Now we can wrap continue to wrap our heads around Traits by going through some examples.


How to Use and Test Traits in Laravel