How to Create and Use Traits in Laravel

Traits are a collection of reusable methods that are accessible in multiple classes. It shares code between classes that are not related by inheritance.

To access these methods in a class first need to define the trait using the use keyword and call the method using $this if it is not a static method otherwise use self::.

In this tutorial, I show how you can create and use Traits in the Controller in Laravel 10.

How to Create and Use Traits in Laravel


Table of Content

  1. Creating a Trait
  2. Create a Route
  3. Using Trait in Controller
  4. Create View
  5. Output
  6. Conclusion

1. Creating a Trait

Trait Declaration

First, need to declare a trait. Traits are essentially PHP files containing code that can be shared among classes.

Here’s the syntax:

<?php 
namespace App;

trait TraitName
{
    /**
    Methods
    **/

}

Organize Your Traits

It is a good practice to have a separate folder to store all the Traits. In your Laravel project, follow these steps:

  • Create a new Traits folder in the app/ directory. This folder will house all your custom traits.
  • Inside the Traits folder, create a file named Common.php. This is where you will define your custom trait.

Defining the Trait

Now, let’s define a Common trait within the Common.php file. In the Common Trait define 2 methods –

  • fun1(): This method returns a string response.
  • status(): Return Active or InActive text based on $status value.
<?php

namespace App\Traits;

trait Common {

   public function fun1(){

       return "Trait response";
   }

   public function status($status = 0){

       $statusText = "InActive";
       if($status == 1){
           $statusText = "Active";
       }

       return $statusText;
   }
}

2. Create a Route

  • Open routes/web.php file.
  • Define 1 routes –
    • / – Load index view.
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PagesController;

Route::get('/', [PagesController::class, 'index'])->name('home');

3. Using Trait in Controller

Once you have created a trait, you can use it in any class by using the use keyword followed by the trait name.

  • Create PagesController Controller.
php artisan make:controller PagesController
  • Open app/Http/Controllers/PagesController.php file.
  • Import Common Trait – use App\Traits\Common;
  • To use it inside the class use the use keyword – use Common;.
  • Create a method –
    • index() – Calling trait function using $this
$this->fun1(); 
$this->status(1);

and assign to the $data Array. Load index view and pass $data Array.

Completed Code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Traits\Common; // Trait

class PagesController extends Controller
{
    use Common; // Trait

    public function index(){
        $data['value1'] = $this->fun1(); // Call trait method
        $data['value2'] = $this->status(1); // Call trait method

        return view('index',$data);
    }

}

4. Create View

Create index.blade.php file in the resources/views/ folder.

Display $value1 and $value2 data.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>How to create and use Traits in Laravel</title>

</head>
<body>
   {{ $value1 }} <br>
   {{ $value2 }} 

</body>
</html>

5. Output

Trait response in view


6. Conclusion

Laravel traits offe­r a dynamic way to promote code reuse­ and modular development. By de­fining these building blocks of code, the­y can be seamlessly inte­grated into multiple classes. This cutting-e­dge feature cre­ates a cleaner and more­ cohesive program, making ongoing maintenance­ easier for deve­lopers.

Abstracting common functionalities and behaviors into separate units with traits can greatly e­nhance the organization and comprehe­nsion of your codebase. Unlike traditional inhe­ritance, traits offer code re­use without limitations by allowing a mix-and-match approach based on your specific class re­quirements.

Traits improve code­ reusability, reduce duplication, and e­nhance developme­nt efficiency when use­d in Laravel. They add flexibility and e­xtensibility by allowing shared functionality across the code­base, enabling easy incorporation into diffe­rent parts of your application to streamline its pe­rformance.

When ne­eding to reuse code­ across multiple classes in Laravel proje­cts, it’s worth considering the use of traits. Traits offe­r modular and reusable code that allows for cle­aner, more efficie­nt, and easily maintainable applications. Embracing the powe­r of traits leads to a productive deve­lopment experie­nce and robust software systems.

If you found this tutorial helpful then don't forget to share.

Leave a Comment