2015-01-07 4 views
1

탄소를 사용하여 created_at의 게시물에 Facebook의 1 min ago과 같은 사람이 읽을 수있는 검색어를 출력하려면 어떻게해야합니까? 문제는 항상 쿼리 결과를 브라우저에서 직접 출력하는 것입니다. 어떻게하면 2015-07-01 12:32:43 대신 1 min ago이거나 다른 사람이 읽을 수 있고 멋지게 통합 할 수 있습니다. 내 컨트롤러에서Carbon을 Laravel 쿼리에 사용

:

$posts = DB::table('posts') 
       ->where('author_id', '=', $id) 
       ->where('created_at', '<', $date) 
       ->orderBy('created_at', 'desc') 
       ->paginate(10); 

    return $posts; 

그런 다음 모든 게시물의 JSON 형식을 반환합니다.

답변

2

전에 당신이 웅변 모델과 함께 제공되는 기능을 사용하는 것이 좋습니다 $appends에 등록하면 배열/JSON 변환에 속성이 포함됩니다.

그리고 당신의 쿼리는 거의 동일 보일 것이다

$posts = Post::where('author_id', '=', $id) 
      ->where('created_at', '<', $date) 
      ->orderBy('created_at', 'desc') 
      ->paginate(10); 
1

시도 :

class Post extends Eloquent { 
    protected $appends = array('created_at_for_humans'); 

    public function getCreatedAtForHumansAttribute(){ 
     return Carbon::parse($this->attributes['created_at'])->diffForHumans(); 
    } 
} 

attribute accessor 반환 형식의 날짜와 그것 때문에 :

foreach ($posts as &$post) { 
    $post->created_at = Carbon::parse($post->created_at)->diffForHumans(); 
} 

return

+0

감사합니다. 효과가 있습니다. 나는'$ post'에서'&'를 제거하기 만하면됩니다. 오식. – user3569641