How to Create & Use Traits in Laravel

Today we’ll learn about Traits. Let’s get started:

Table of Contents

  1. What are Traits?
  2. Create a Trait
  3. Connect Trait to Model
  4. Use Trait in Controller

What are Traits?

A Trait is simply a group of methods that you want to include within another class. Let’s read the exact definition of Traits from the PHP site:

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. The semantics of the combination of Traits and classes is defined in a way which reduces complexity, and avoids the typical problems associated with multiple inheritance and Mixins.

A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

Create a Trait

Assume we have a Post model & controller. We’ll create a Trait to generate post slug.

In your project’s app folder, make a folder called Traits. Navigate to app>Traits folder and create a file called PostSlugTrait.php. Open the file and paste this code:

PostSlugTrait.php
<?php

namespace App\Traits;

trait PostSlugTrait
{
    public function generateSlug($string)
    {
        return strtolower(preg_replace(
            ['/[^\w\s]+/', '/\s+/'],
            ['', '-'],
            $string
        ));
    }
}

That’s it. We’ve created a Trait.

Connect Trait to Model

In this step, we’re going to connect the Trait with the Post model. From the app folder, open Post.php & add use PostSlugTrait; like this:

Post.php
<?php

namespace App;

use App\Traits\PostSlugTrait;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use PostSlugTrait;
}

Great, we’ve connected PostSlugTrait to the Post model.

Use Trait in Controller

This is the last step. Now we’re going to use the PostSlugTrait. Open the PostController & test the trait like this:

PostController.php
<?php

namespace App\Http\Controllers;

use App\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function addPost()
    {
        $post = new Post();
        $post->title = "Title 1";
        // the Trait will generate slug from post title
        $post->slug = $post->generateSlug($post->title); // title-1
        $post->save();
    }
}

I hope you’ve got the idea about Traits. Thank you.


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.