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.
Table of Content
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 theapp/
directory. This folder will house all your custom traits. - Inside the
Traits
folder, create a file namedCommon.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
orInActive
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
–
- index() – Calling trait function using
$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
6. Conclusion
Laravel traits offer a dynamic way to promote code reuse and modular development. By defining these building blocks of code, they can be seamlessly integrated into multiple classes. This cutting-edge feature creates a cleaner and more cohesive program, making ongoing maintenance easier for developers.
Abstracting common functionalities and behaviors into separate units with traits can greatly enhance the organization and comprehension of your codebase. Unlike traditional inheritance, traits offer code reuse without limitations by allowing a mix-and-match approach based on your specific class requirements.
Traits improve code reusability, reduce duplication, and enhance development efficiency when used in Laravel. They add flexibility and extensibility by allowing shared functionality across the codebase, enabling easy incorporation into different parts of your application to streamline its performance.
When needing to reuse code across multiple classes in Laravel projects, it’s worth considering the use of traits. Traits offer modular and reusable code that allows for cleaner, more efficient, and easily maintainable applications. Embracing the power of traits leads to a productive development experience and robust software systems.
If you found this tutorial helpful then don't forget to share.