Packy
Packy

Reputation: 3573

Laravel always return date column with carbon

Is there a way to always make the dates from a column return using carbon?

Let say I have a Challenges model/table with date_end column.

When I do this call in my ChallengesController it returns all the challenges in json for my app:

public function index()
    {
      return response()->json([
        'status'=>'success',
        'challenges' => Auth::user()->challenges,
      ]);
    }

But the date is still MySQL format. I know I can do :

public function index()
{
      $challenges = Auth::user()->challenges;

      foreach ( $challenges as $challenge){
         $challenge['humandate'] = $challenge->date_end->diffForHumans();
       }

      return response()->json([
            'status'=>'success',
            'challenges' => $challenges,
      ]);
}

then get the date via challenge.humandate But is there a cleaner way?

Upvotes: 2

Views: 3996

Answers (2)

user320487
user320487

Reputation:

As @Castis points out, you can use attribute mutators and accessors to modify the data is it goes to the model and as it comes from the model. In your case define getCreatedAtAttribute method, for example, and return from it Carbon and the created_at field parsed into it.

Upvotes: 5

Ohgodwhy
Ohgodwhy

Reputation: 50787

In your model you can declare which columns should be converted to Carbon instances by adding them to the protected $dates array:

protected $dates = ['created_at', 'updated_at', 'date_end'];

Of course the first two are only necessary if you're using the ->timestamps() method in your migrations.

Upvotes: 9

Related Questions