DEV Community

Arman Rahman
Arman Rahman

Posted on

2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs