How to Create and Use Traits in Laravel 8

Traits are a collection of reusable methods that are accessible in multiple classes.

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

How to create and use Traits in Laravel 8


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

1. Creating Trait

Syntax – 

namespace App;

trait TraitName


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

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

Completed Code


namespace App\Traits;

trait Common {

   public function fun1(){

      return "Trait response";

   public function status($status = 0){

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

      return $statusText;

2. Route

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

Completed Code


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

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

Completed Code


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>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>How to create and use Traits in Laravel 8</title>

   {{ $value1 }} <br>
   {{ $value2 }} 


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 multiple traits and use them in the controller.

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

Leave a Comment