DEV Community

Cover image for How to create and use traits in Laravel
Snehal Rajeev Moon
Snehal Rajeev Moon

Posted on

How to create and use traits in Laravel

Hello Artisans,

Hey there want to know about traits, and how can we use it in Laravel then you need to read this blog and try to implement in your project.

  • A trait is a group of methods that can be included into a class. Basically it helps us to reuse our code if the same functionality used in different pages, it also helps us to use different sets of method independently in classes living in different class hierarchies.

So let's get started with an example of how to create a trait in Laravel:

  • Create a new file in the app/Traits directory and give it a descriptive name, such as MyTrait.php.

  • In the newly created file, add the following code to define a trait:

<?php

namespace App\Traits;

trait MyTrait
{
    public function hello()
    {
        return 'This is my first Trait example';
    }
}
Enter fullscreen mode Exit fullscreen mode
  • To use the trait in a class, you can use the use keyword followed by the namespace and trait name in the class. For example:
<?php

namespace App\Models;

use App\Traits\MyTrait;

class User
{
    use MyTrait;
}
Enter fullscreen mode Exit fullscreen mode
  • Now you can call the hello method from the User class:
$user = new User();
echo $user->hello();
Enter fullscreen mode Exit fullscreen mode
  • This is a basic example of how to create a trait in Laravel. You can add as many methods as you like to a trait, and a class can use multiple traits if needed.

  • It's also possible to override the methods in a trait in the class that uses the trait.

Save and like the post for your reference, also you can share it on Twitter, Linkedin and follow me for more information about laravel.

Thank you!!
Happy Reading 🦄 ❤️

Oldest comments (0)