ambe5950
ambe5950

Reputation: 75

Always modify returned values from laravel model

So I have a model, Post that has no methods defined within it.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

use DB;

class Post extends Model
{

}

From a controller, I make calls to that model like:

return view('pages.post', ['post' => Post::where('url_route', '=', $url_route)->first()]

This works fine, but I now want to format the date column that is returned from that request, every time that model is called. Is there a way to modify the returned array without defining a new method?

I am new to Laravel to thanks for the help. Just trying to figure out the most efficient way of doing things within the framework...

Upvotes: 0

Views: 1608

Answers (1)

user2094178
user2094178

Reputation: 9454

If your model has $timestamps set to true, the created_at and updated_at fields are natively a Carbon instance.

This means you can format the date in the view like this as a basic example:

$post->updated_at->format('Y-m-d H:i:s')

Carbon instances allow you to leverage its extensive api as you can see at http://carbon.nesbot.com

If you would like to do the same for another field other than created_at and updated_at, you can add an extra property in your model:

protected $dates = ['added_on']

The fields you specify in the array will be treated as Carbon instances.

Upvotes: 2

Related Questions