DEV Community

Arman Rahman
Arman Rahman

Posted on

Create Trait and use in Laravel

Trait is a concept of OOP. Where you can add methods, properties, or any other code that you want to reuse across multiple classes.
After that you can use those functions into other classes by using a keyword use.

Create a new PHP file for your trai wiyh .php extension and follow the naming convention of customTraitName.php.

Define your trait on trait file and define your trait using the trait keyword. You can add methods, properties.

app/Traits/customTrait.php
Enter fullscreen mode Exit fullscreen mode
namespace App\Traits;

trait customTrait
{
    public function yourFunction()
    {
        // Your code here
    }

    public function yourAnotherFunction()
    {
        // Your code here
    }
}
Enter fullscreen mode Exit fullscreen mode

Now go you your class where you want to access those methods, properties. call use customTrait after you class starts.

use App\Traits\customTrait;

class YourClass
{
    use customTrait;

    public function someMethod()
    {
        // Now you can call those methods, properties with this-> instance -
        $this->yourFunction();
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)