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 9.

How to Create and Use Traits in Laravel


Contents

  1. Creating Trait
  2. Route
  3. Controller
  4. View
  5. Output
  6. Conclusion

1. Creating Trait

Syntax – 

<?php 
namespace App;

trait TraitName
{
    /**
    Methods
    **/

}

Create a new folder Traits in app/ to store all Traits.

  • Create Common.php file.
  • Set namespace to App\Traits.
  • I set the trait name to Common.
  • Created 2 methods –
    • fun1() – Return string response.
    • status() – Return Active or InActive text based on $status value.

Completed Code

<?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. Route

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

Completed Code

<?php

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

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

3. Controller

  • 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. View

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

Display $value1 and $value2 data.

Completed Code

<!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

Use Traits to perform any reusable operation across multiple classes like – file upload, calculations, database manipulation, etc.

You can import more than one trait in your controller and use it.

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

Leave a Comment