DEV Community

Rohit Urane
Rohit Urane

Posted on

How do you make your traits in laravel?

Image description

Hi Guys,

In this article, We are studying traits in laravel. Traits are a way to reuse code in laravel. You can't instantiate on their own. It provides reusability, flexibility, and adherence to code. After including traits in class, it gives them additional methods. Avoiding the need for duplicate code blocks encourages clean and modular programming.  

How to make own traits in laravel application?

Make a traits file:

You can create a traits folder inside the app directory. Make a ShareTraits file inside the traits folder.

 

<?php
namespace App\Traits;

trait ShareTraits {
    public function share($article) {
        return 'Share the article';
    }
}
Enter fullscreen mode Exit fullscreen mode

Now, you can use this trait in other classes.

<?php
namespace App\Http\Controllers;

use App\Traits\ShareTraits;
use App\Http\Controller;

class Article extends Controller{
    use ShareTraits;

}
Enter fullscreen mode Exit fullscreen mode

After Importing traits, we can use the share() method in the controller. You can import this trait into any class. So that access their functions. 

Please check the rest of the article on Link

Top comments (0)