Getting difference in days between created_at and updated_at using accessors in eloquent model

Accessors helps to change particular model values going through each of it if used in loop in view. Moreover, it also can be used to change a sole model value.

Suppose, if we need to get post updating gap in days between created_at and updated_at field for a particular post, we can use following snippet in model

Step 01: In Model

public function getUpdatingGapAttribute() {   
    return $this->created_at->diffInDays($this->updated_at);
}

Above, carbon operations are performed since both created_at and updated_at are date fields in laravel.

Here, Post updating gap means number days between post creation and updating that is after how many days a post is updated from being creation.

Step 02: In Controller

$posts = Post::select([ 'id', 'user_id' ,'title', 'created_at','updated_at'])->get()->sortByDesc('updating_gap');

Above, the thing to note is after eloquent fetch applying collection method sortByDesc which takes the newly created accessor "updating_gap" as parameter and uses this for sorting rows in descending order.

Step 03: In view

Lastly, using accessor in view is straight forward with either foreach or forelse loop like following

// foreach
@foreach( $posts as $post )
{{ $post->updating_gap }}
@endforeach

// forelse - it has additional option of putting empty texts during loop if there are no data
@forelse( $posts as $post) {{ $post->updating_gap }} @empty No posts yet. @endforelse

Related Posts