A trait is similar to an abstract class which cannot be instantiated on its own.
Traits is a mechanism for code reuse in single inheritance languages
in this case PHP.
Now whenever you find yourself that your model's for instance are getting too bloated and you are using the same functionallity over and over in different models then you might think as a tell tail sign of using a trait.
Now you might think since we have same functionallity why not using a template design pattern instead?! However since all the models in Laravel they do extend a base model you really should be careful with interitance use.
Laravel by default uses a lot of traits example if you want to use softDeletes()
then simply you just pull a trait to bring in functionallity to that model.
Here is a practical use of a trait. One of my apps it happens that I want to keep track of all updates that are happening on my database and store them in a different table. So if I want to track a model activity then I simply use this trait:
<?php
namespace App;
use App\Activity;
trait RecordsActivity
{
protected static function bootRecordsActivity()
{
static::created(function ($thread) {
$thread->recordActivity('created');
});
}
protected function recordActivity($event)
{
Activity::create([
'user_id' => auth()->id(),
'type' => $event . '-' . strtolower((new \ReflectionClass($this))->getShortName()),
'subject_id' => $this->id,
'subject_type' => get_class($this),
]);
}
}
So whenever I want to track a model activity I simply pull in this trait,
use RecordsActivity;
instead of bloating the model with extra code and even worst reapating code in different models, or making it more spageti using class inheritance.
Or in some build in traits in Laravel when you need them like softDeletes you just have to pull them in, instead of having them ready in the base class even when you dont need them.