Meera
Meera

Reputation: 103

Unix time Format not working in Laravel where clause

I have a query in Laravel query builder like this. And I want to get data from a particular year

$query = blogs::where(array('blogs.status' => '1','blog_categories.status' => '1','categories.status' => '1','blogs.published' => '1'));

if (isset($year) and $year != NULL)$query->where("FROM_UNIXTIME(blogs.pubdate, '%Y')", '=', $year); 
    $result= $query->leftJoin('blog_categories', 'blog_categories.blogid', '=', 'blogs.blogid')->leftJoin('categories', 'blog_categories.catid', '=', 'categories.catid')->orderBy('blogs.publisheddate', 'desc')->count();

I got an error 'FROM_UNIXTIME' command. Here my 'blogs.pubdate' is in timestamp format (1456313400).Any idea?

Thanks for helping.

Upvotes: 1

Views: 1627

Answers (1)

chanafdo
chanafdo

Reputation: 5124

You need to use raw expressions

$query = blogs::where([
    'blogs.status' => '1',
    'blog_categories.status' => '1',
    'categories.status' => '1',
    'blogs.published' => '1'
]);

if (isset($year) && $year != NULL) {
    $query->whereRaw("FROM_UNIXTIME(blogs.pubdate, '%Y') = {$year}"); 
}

$result= $query->leftJoin('blog_categories', 'blog_categories.blogid', '=', 'blogs.blogid')
    ->leftJoin('categories', 'blog_categories.catid', '=', 'categories.catid')
    ->orderBy('blogs.publisheddate', 'desc')
    ->count();

Upvotes: 1

Related Questions