dimanche 12 février 2017

Laravel - Make only 3 functions for getters and setters

Vote count: 0

I believe that there are more developers who need to have a locale date format (shown in app front end) than the ones who use the default format in browsers which is 12/22/2016.

So i have made a small trait in my Laravel project for standard dates like created_at, updated_at and deleted_at:

attributes['created_at'] = Carbon::parse($date);
    }

    // convert the UTC format to local format
    public function getCreatedAtAttribute($date)
    {
        return Carbon::parse($date)->format($this->localFormat);
    }

    // get diffForHumans for this attribute
    public function getCreatedAtHumanAttribute()
    {
        return Carbon::parse($this->attributes['created_at'])->diffForHumans();
    }

    // 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 local format
    public function getUpdatedAtAttribute($date)
    {
        return Carbon::parse($date)->format($this->localFormat);
    }

    // get diffForHumans for this attribute
    public function getUpdatedAtHumanAttribute()
    {
        return Carbon::parse($this->attributes['updated_at'])->diffForHumans();
    }

    // save the date in UTC format in DB table
    public function setPublishedAtAttribute($date)
    {
        $this->attributes['published_at'] = Carbon::parse($date);
    }

    // convert the UTC format to local format
    public function getPublishedAtAttribute($date)
    {    
        return Carbon::parse($date)->format($this->localFormat);
    }

    // get diffForHumans for this attribute
    public function getPublishedAtHumanAttribute()
    {
        return Carbon::parse($this->attributes['published_at'])->diffForHumans();
    }

    // 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 local format
    public function getDeletedAtAttribute($date)
    {    
        return Carbon::parse($date)->format($this->localFormat);
    }

    // get diffForHumans for this attribute
    public function getDeletedAtHumanAttribute()
    {
        return Carbon::parse($this->attributes['deleted_at'])->diffForHumans();
    }

}

There are actually only 3 functions for those dates and those are:

set the date so it can be saved with date time picker
get the date in locale format (22.12.2016 14:39)
get the date in human readable form

So my question is how to make this trait to have only 3 functions instead of repeating it all the time for every single variable? Is this doable?

asked 20 secs ago

Let's block ads! (Why?)



Laravel - Make only 3 functions for getters and setters

Aucun commentaire:

Enregistrer un commentaire