A trait is a collection of attributes and methods that define the functionality of a class. Traits are used in Laravel to share behaviour between classes, and a class can have several Traits.
A Trait is specified similarly to a class's attributes and methods, but it is not a separate class that may be instantiated. Instead, a Trait can be applied to a class (used), and the Trait's properties and methods can be used in the same manner that the class's properties and methods are. A Trait allows a class to utilise the properties and methods described within the Trait, minimizing code redundancy.
Laravel Traits promote code readability and reuse by preventing code repetition. Traits are frequently used in Laravel for repeating properties of a class, eliminating code repetition.
The example below is a basic Laravel Trait that can be used to apply the "soft deletes" capability to a model.
<?php
namespace App\Traits;
trait SoftDeletes
{
protected $deleted_at = null;
public function delete()
{
$this->deleted_at = date('Y-m-d H:i:s');
$this->save();
}
public function restore()
{
$this->deleted_at = null;
$this->save();
}
public function forceDelete()
{
$this->delete();
$this->forceDelete();
}
public function getDeletedAtAttribute($value)
{
return $value ? date('Y-m-d H:i:s', strtotime($value)) : null;
}
public function scopeDeleted($query)
{
return $query->whereNotNull('deleted_at');
}
}
The SoftDeletes Trait includes a $deleted_at property and three methods, delete, restore, and forceDelete, which mark a record as "soft-deleted", restore a previously soft-deleted record, and permanently destroy a record, respectively. The scopeDeleted method searches for soft-deleted entries, while the getDeletedAttribute method populates the deleted_at attribute.
Simply use the use keyword to include this Trait in a model, as shown below:
<?php
namespace App\Models;
use App\Traits\SoftDeletes;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use SoftDeletes;
// ...
}
The SoftDeletes Trait is used by the Post model in this example to implement the "soft deletes" feature.