How to make a Trait in Laravel

倖福魔咒の 提交于 2019-12-31 10:33:13

问题


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
{
    protected $newDateFormat = 'd.m.Y H:i';


    // save the date in UTC format in DB table
    public function setCreatedAtAttribute($date){

        $this->attributes['created_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getCreatedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }

    // save the date in UTC format in DB table
    public function setUpdatedAtAttribute($date){

        $this->attributes['updated_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getUpdatedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }

    // save the date in UTC format in DB table
    public function setDeletedAtAttribute($date){

        $this->attributes['deleted_at'] = Carbon::parse($date);

    }

    // convert the UTC format to my format
    public function getDeletedAtAttribute($date){

        return Carbon::parse($date)->format($this->newDateFormat);

    }
}

And how to apply it for example on a User Model class...


回答1:


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



来源:https://stackoverflow.com/questions/40288657/how-to-make-a-trait-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!