How to use traits in laravel?

Member

by gilbert , in category: PHP General , 7 months ago

How to use traits in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by domenico , 7 months ago

@gilbert 

To use traits in Laravel, you need to follow these steps:

  1. Create a new trait file: First, create a new file inside the app/Traits directory (you can create this directory if it doesn't exist). For example, let's create a Auditable.php trait:
1
2
3
4
5
6
namespace AppTraits;

trait Auditable
{
    // trait methods and properties here...
}


  1. Add methods and properties to the trait: Inside the trait file, you can define methods and properties that you want to reuse across multiple classes. For example, let's add an createdBy() method to get the user who created the record:
1
2
3
4
5
6
use IlluminateSupportFacadesAuth;

public function createdBy()
{
    return Auth::user();
}


  1. Use the trait in a class: To use the trait in a class, simply add use TraitName; at the top of the class definition. For example, let's use the Auditable trait in a Post model:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
namespace AppModels;

use IlluminateDatabaseEloquentModel;
use AppTraitsAuditable;

class Post extends Model
{
    use Auditable;

    // model code here...
}


  1. Access the trait methods and properties: Once the trait is used in a class, you can access its methods and properties using the class instance. For example, to get the user who created a post, you can call the createdBy() method:
1
2
$post = new Post;
$user = $post->createdBy();


That's it! You can now reuse the trait methods and properties in multiple classes without duplicating code. Remember to import the trait namespace at the top of any class where you want to use it.