Ad

Object Of Class Closure Could Not Be Converted To String In Laravel

- 1 answer

Object of class Closure could not be converted to string in laravel, i am trying get post by month and year

here is controller

public function getPostsByArchive($slug)
{
   $archiveposts = \Canvas\Post::whereDate('published_at', date('F-Y'),function ($query) use ($slug) {
                $query->where('published_at', date('F-Y'), $slug);
            })->published()->orderByDesc('published_at')->get();
      return view('posts.archive', compact('archiveposts'));
}

here is route

Route::get('archive/{slug}', '[email protected]')->name('posts.archive');
Ad

Answer

You're using whereDate wrongly, passing a closure as 3rd arg causes an error. Instead you may use whereRaw and format your published_at column using MySQL's date_format function:

$archiveposts = \Canvas\Post
        ::whereRaw("date_format(published_at, '%M-%Y') = ?", [$slug])
        ->published()
        ->orderByDesc('published_at')
        ->get();

return view('posts.archive', compact('archiveposts'));
Ad
source: stackoverflow.com
Ad