You are here

How do you make your traits in laravel?

Submitted by rockstar_r on Thu, 05/23/2024 - 20:18

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';
}
}

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;

}
Read More