How to make a Trait in Laravel

前端 未结 3 2025
轻奢々
轻奢々 2021-01-31 15:08

Where to make the file if i want to use this trait on my Models

How should this file look like if i want to have this trait inside:

trait FormatDates
{
          


        
3条回答
  •  温柔的废话
    2021-01-31 15:52

    Well, laravel follows PSR-4 so you should place your traits in:

    app/Traits

    You then need to make sure you namespace your trait with that path, so place:

    namespace App\Traits;
    

    At the top of your trait

    Then make sure when you save the file, the file name matches the trait name. So, if your trait is called FormatDates you need to save the file as FormatDates.php

    Then 'use' it in your User model by adding:

    use App\Traits\FormatDates;
    

    at the top of your model, but below your namespace

    and then add:

    use FormatDates;
    

    just inside the class, so for your User model, assuming you are using the laravel default, you would get:

    use App\Traits\FormatDates;
    
    class User extends Authenticatable
    {
        use Notifiable, FormatDates;
    
    ...
    }
    

    And remember to dump the autoloader:

    composer dump-autoload

提交回复
热议问题