Backend Development 4 min read

Understanding PHP Traits and Their Use in Laravel

This article explains the concept of PHP Traits, how they overcome single inheritance limitations, provides clear code examples of defining and using Traits in plain PHP, and demonstrates practical integration of Traits within Laravel applications for reusable functionality.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Understanding PHP Traits and Their Use in Laravel

PHP, being a single‑inheritance language, restricts a class to inherit from only one parent, which can lead to code duplication when similar functionality is needed across multiple classes. Since PHP 5.4, the language introduced Traits as a code‑reuse mechanism that allows developers to compose methods horizontally without using multiple inheritance.

A Trait is essentially a collection of methods that can be inserted into a class; it cannot be instantiated on its own. The official definition describes Traits as a way to reduce the limitations of single inheritance by allowing the reuse of methods from several independent class hierarchies.

Example of a simple Trait definition:

<?php
trait SharePost {
    public function share($item) {
        return 'share this post';
    }
}

Using the Trait in other classes:

<?php
class Post {
    use SharePost;
}

class Comment {
    use SharePost;
}

When objects of Post or Comment are created, they can directly call the share() method provided by the Trait:

<?php
$post = new Post();
echo $post->share(''); // outputs 'share this post'

$comment = new Comment();
echo $comment->share(''); // outputs 'share this post'

In Laravel, Traits are commonly placed in the app/Http/Traits directory. After creating a file such as BrandsTrait.php , it can be imported and used inside a controller:

<?php
use App\Http\Traits\BrandsTrait;

class YourController extends Controller {
    use BrandsTrait;

    public function addProduct() {
        $brands = $this->brandsAll();
        // further logic
    }
}

The BrandsTrait itself might look like this:

<?php
namespace App\Http\Traits;

use App\Brand;

trait BrandsTrait {
    public function brandsAll() {
        // Retrieve all brands from the Brand model
        $brands = Brand::all();
        return $brands;
    }
}

By encapsulating reusable methods in Traits, developers can keep their code DRY, simplify maintenance, and quickly add common functionality across different parts of a Laravel project.

backendphpoopcode reuseLaravelTraits
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.