Canvas: get post by date like month or year

Created on 11 Mar 2020  路  2Comments  路  Source: austintoddj/canvas

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

question

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:

$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)).

All 2 comments

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'));

}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

armancodes picture armancodes  路  7Comments

karlmonson picture karlmonson  路  10Comments

iiCe89 picture iiCe89  路  3Comments

hide-me picture hide-me  路  5Comments

austintoddj picture austintoddj  路  10Comments