i want to get post by date like month or year,
please anyone can tell how can i get this i am new at laravel
Hi @kama003,
Laravel has some helpful methods for the Query Builder (and Eloquent) that allow us to filter a query by month, year, day, etc. Here's the documentation. Scroll down to whereDate / whereMonth / whereDay / whereYear / whereTime.
A simple example for Posts would be:
$posts = Post::whereYear('published_at', '2020')->get();
// or ->simplePaginate(10); instead of ->get(); if you want to paginate the posts.
$posts = Post::whereMonth('published_at', '6')->get();
You can, of course, replace the year and month you are looking for with the request parameter (request('year', Date::now()->year)).
hi @mikemand
I have route like this i want to get post according to this route
how to use whereyear and wheremonth both at same time in laravel
<a href="/archive/{{ $archive->published_at->format('F') }}/{{ $archive->published_at->format('Y') }}">{{ $archive->published_at->format('F, Y') }}</a>
Route::get('archive/{m}/{y}', 'PostController@getPostsByArchive')->name('posts.archive');
public function getPostsByArchive( $m,$y)
{
$archiveposts = \Canvas\Post::whereYear('published_at', $y)->whereMonth('published_at', $m)->published()->orderByDesc('published_at')->get();
return view('posts.archive', compact('archiveposts'));
}
Most helpful comment
Hi @kama003,
Laravel has some helpful methods for the Query Builder (and Eloquent) that allow us to filter a query by month, year, day, etc. Here's the documentation. Scroll down to
whereDate / whereMonth / whereDay / whereYear / whereTime.A simple example for Posts would be:
You can, of course, replace the year and month you are looking for with the request parameter (
request('year', Date::now()->year)).