@gilbert
To use traits in Laravel, you need to follow these steps:
- 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...
}
|
- 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();
}
|
- 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...
}
|
- 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.