How to Create & Use Traits in Laravel
Today we’ll learn about Traits. Let’s get started:
Table of Contents
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:
<?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:
<?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:
<?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. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)