0

I have a uploaded_at column in database having type as timestamp.

$from = date("d-m-Y", strtotime("-2 months"));
$data = Post::where('uploaded_at' , '>' , $from)->paginate(20);

This piece of code is giving all the data from the post table where I needed only the last 2 months post.

3
  • I guess you're using the wrong date format. Try Y-m-d. Sorry, that's what Tushar already wrote below. Commented Mar 5, 2020 at 7:50
  • i tried that format in the beginning but it didn't work. i even checked if there was problem with the table using phpmyadmin by this query which gives me proper output...[ SELECT * FROM posts WHERE uploaded_at > '2020-1-1' ]... Commented Mar 5, 2020 at 9:12
  • 1
    If the column type really is TIMESTAMP, I suppose you have to use Y-m-d 00:00:00 including time information, see dev.mysql.com/doc/refman/8.0/en/… Commented Mar 5, 2020 at 9:45

3 Answers 3

1

Try this code

$from = date("Y-m-d", strtotime("-2 months"));
$data = Post::whereDate('uploaded_at' , '>=' , $from)->paginate(20);
Sign up to request clarification or add additional context in comments.

6 Comments

i tried but still the same...to check if my database table had any problem i even checked using phpmyadmin which gave me proper results.query: [ SELECT * FROM posts WHERE uploaded_at > '2020-1-1' ]
i tried using your code showing 0 results. can it be because its in the localhost ...
Can you check last executed query, for check the query. query is ok or not
I mean can you check the query builder build which query. Is it create expected as your requirement?
Please add some explanation to your answer by editing it, such that others can learn from it
|
1

Laravel has a default package, named Carbon Which can easily handle do this, like this :

$date = Carbon::now();
$previous = $date->subMonths(2);
$data =Post::whereBetween('uploaded_at', [$previous, $date])->paginate(20);

Don't forget to use Carbon\Carbon; on th top.

Hope this helps..

3 Comments

tried this but showing the same results as tushar's.
sorry there was no problem with the query....after installing xampp again it got fixed.... i think the problem was with my mysql ... thank you
and your answer worked for me too but i preferred tushars because it uses builtin php functions.... and whereBetween didn't work for me... This worked: $date = Carbon::now(); $previous = $date->subMonths(3); $data = Post::where('uploaded_at' , '>' , $previous)->paginate(20);
0

Use the whereDate() function to compare date:

$data = Post::whereDate('uploaded_at' , '>' , $from)->paginate(20);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.