Showing posts with label Laravel Trait. Show all posts
Showing posts with label Laravel Trait. Show all posts

Saturday, February 25, 2017

A simple guide to using Traits in Laravel 5

Its great if we can use trait in our application. Laravel has the ability to give us that freedom to use trait. Laravel is a strong php based framework today. At first we have to create a trait, but its nothing but a php class except we use here a keyword named 'trait' & surely this class has no constructor as it cannot be instantiated. So lets start with use of trait.

First we have to create a php file named "TestTrait.php" as follows:

namespace App\Trait;

trait TestTrait {
    public function someFunction() {
        
    }
}

I think you have already have good knowledge about namespace described in Laravel.

Now we have to use this trait in some Controller or Service etc...

Lets see an example of use of trait in Controller.

First we have to import "TestTrait" in our Controller as follows:

//First step is import
use App\Trait\TestTrait;
class TalentMapperController extends Controller
{
    //Second step is tell our Controller to use trait
    use TestTrait;
    
    public function __construct() {
        //Third & final step is apply functions from here
        super::someFunction();
    }
}