1
votes

I have created mutator date function in model to convert the created_at date into human readable time using diffForHumans(). I have done the following

public function setDateAttribute($value){
    return \Carbon\Carbon::parse($value)->diffForHumans();
}

It works fine but it affects in all. it is possible to apply this mutator only on the specified function of the controller rather than all function

1
what do you mean by 'affects in all' ? mutators only works when you call them. - Tharaka Dilshan
I want to call them on the specific function of the controller.currently it parses and set date in another function of the controller. that I don't want I just want my mutator function in my index method did not edit or show methods - khandar shailesh
edit your question and put a sample code of where you did use this mutator - Tharaka Dilshan
public function getLeadProductDateAttribute($value){ return \Carbon\Carbon::parse($value)->diffForHumans(); } this is my mutator function. it is call automatically. but i want to call that function on specific controller function - khandar shailesh
again, this is function declaration, show us where did you use this. - Tharaka Dilshan

1 Answers

0
votes

A small logic in the mutator would do the job:-

    public function setDateAttribute($value){
       if ( request()->path() === "/yourURL/To/IndexMethod"){ 
         return $this->attributes['date'] = \Carbon\Carbon::parse($value)->diffForHumans();
       } else {
         return $this->attributes['date'] = $value;
       }
    }

the idea is to check by the url.

getting request path helper

EDIT

Comparison using route name is better, as exact path can contain id/slugs.

public function setDateAttribute($value){
       if ( \Route::currentRouteName() === "/yourRouteName/To/IndexMethod"){ 
         return $this->attributes['date'] = \Carbon\Carbon::parse($value)->diffForHumans();
       } else {
         return $this->attributes['date'] = $value;
       }
    }

getting route name