Cannot compare Carbon instances in Laravel 5? - php

I am working with the fullcalendar plugin and I am trying to fetch all the events in my database after and before a certain date. Full calendar paginates the events by adding paramaters called 'start' and 'end'. I am able to parse these in to Carbon instances like so:
Carbon::parse($data['start']);
Carbon::parse($data['end']);
Now this is working fine:
$events = $this->event->where('user_id', auth()->user()->id)
->get();
But this is not:
$events = $this->event->where('user_id', auth()->user()->id)
->where('start', '>=', Carbon::parse($data['start']))
->where('end', '<=', Carbon::parse($data['end']))
->get();
Why am I not getting events published between these two dates with the second approach. When I run the first approach, it works fine and fetches all the events and publishes them on the current page but unfortunately it is also fetching a whole lot of events that don't need fetching.
After listening to the DB queries, the event query was like:
select * from events where user_id = ? and start >= ? and end <= ?

This was a small mistake on my end where I was not setting the end date for the event in my DB and hence the query where all the events for the authenticated users was working correctly.
In fact the query for >= start would also have worked alone but the the <= end was creating as issue since end was null and hence Eloquent was not returning any models.

Related

Laravel query builder count rows by day SQL db::raw

I've got a Laravel 8 application whereby I need to count the number of total applications for each day and output a count of the data in the most efficient way, for instance, 500 applications on 1st, 1,000 applications on 2nd and so fourth, depending on how many applications there are each day.
I'm using DB::raw() to count my rows, however, Laravel's timestamps by default includes the hours, minutes and seconds as part of the date, and so this isn't going to work for me, I need to format the date to exclude this and just contain the day.
My query doesn't seem to be returning anything, and no error either, so I think there's something wrong with my first DB::raw(), it doesn't seem to be formatted the created_at column at all, what am I missing?
Application::whereBetween('created_at', [$from, $to])
->select(DB::raw('DATE_FORMAT("created_at, %Y-%m-%d")'), DB::raw('count(*) as applications'))
->groupBy('created_at')
->get();
You can use groupByRaw()
Application::whereBetween('created_at', [$from, $to])
->select(DB::raw('DATE_FORMAT(created_at, "%Y-%m-%d")'), DB::raw('count(*) as applications'))
->groupByRaw('DATE_FORMAT(created_at, "%Y-%m-%d")')
->get();
Also, you can use selectRaw() instead of select(DB::raw)

How to retrieve records from database table in Laravel and prevent those which are expired

So I have a table in MySQL which looks like this
these are basically ads that are posted by users. Duration column in this table is about for how many days the User wants to show their ad. that means if user choose to post ad for 3 days i should not just show after 3 days that means it will expire after three days. Now i Want to retrieve only those records which are not expired.
I have searched a lot but could not find a way to do this. Kindly give me a solution or refer to a link where i can possibly find the solution.
Right now I am using this script to get the records with simple pagination
$items=Post::with('items','users')->paginate(12);
$categories = DB::table('item_categories')->get();
return view('search_post', compact('items','categories'));
You should do an Where Clause with your paginate.
as stated here: https://stackoverflow.com/a/50903963/3808783
like:
$items=Post::with('items','users')
->where('created_at', '<=', Carbon::now()->addDays(3))
->paginate(12);
Use Carbon to do so.
Simply add duration to created_at with Carbon addDay($duration) method.
Then return your posts where the result is >= to today().
So I changed my table to this
And using this script
$items=Post::with('items','users')->where('duration','>=',\Carbon\Carbon::now() )->paginate(12);
$categories = DB::table('item_categories')->get();
return view('search_post', compact('items','categories'));
It is working perfectly. Thanks to every one.

Laravel Eloquent find rows where date older than 2 days

I'm trying to fetch rows based on the "created_at" field that are older than (for example) 2 days.
I'm using Laravel Eloquent. Can somebody help me with this?
You can use Carbon subDays() like below:
$data = YOURMODEL::where('created_at', '<=', Carbon::now()->subDays(2)->toDateTimeString())->get();
You can use the whereDate() eloquent method to run a query against dates.
Model::whereDate('created_at', '<=', now()->subDays(2)->setTime(0, 0, 0)->toDateTimeString())->get();
The now() is a laravel helper function to get a carbon instance of the current date and time.
NOTE: We set the time using the setTime() method so that it starts from the beginning of the day.
Update: It is also possible to use ->startOfDay().

How to select from database using laravel where clause and created_at

I want to select all the data on a database using laravel db query or Eloquent ORM. So i want all the data that are other than 3 days from the day they where created. Data 'A' is created on 15th i come in on 16th to check, i won't see Data 'A' but i may see others older than 3 days or equal to 3 days. If i come back on the 18th or 19th i should see Data 'A', obviously because it now older than 3 days or equal to.
so i wrote this code that is not working below
$users = DB::table('matched_users')->where( 'created_at', '>=',
Carbon::now()->subDays(3));
so can anyone correct this for me.
when i did that it work but it shows both someone that his date is just one day one. so is that not enough code
Data Name - created_at
ozil 21/04/2012 16:09:22
mark 21/04/2012 16:09:22
cyril 22/04/2012 16:19:21
so today is 25/04/2012 if run the query of run the above query as it is i get all the result back.
But if change the >= to <= the result is an empty collection
I guess you mean 'older than 3 days from the day they where created'. In this case the query should look like this:
DB::table('matched_users')->where('created_at', '<=', Carbon::now()->subDays(3));
$users = DB::table('matched_users')->whereDate( 'created_at', '<=', Carbon::now()->subDays(3))->get();
is the right way to write the code

Filter SQL database query by timestamp, backend in PHP using Laravel

So I'm trying to build a query to my SQL database from my backend (that's written in php with Laravel). I have a table in my database with a column that's titled "created_at", carrying values of the 'timestamp'-type. What I want to do is, when I send a query to my database, to only pick the rows (or instances, I guess) of my table that are created 30 days or less from the current date. I've tried experimenting back and forth with the 'where' keyword, but I couldn't get it to work as I wanted it to.
When I browse the table in my database, the dates are written in the format "YYYY-MM-DD hh:mm:ss" but I'm not sure how to compare them when they're in this format, and I don't know how to convert them whilst doing a query. I've looked at the whereBetween() method in Laravel but I didn't get that to work since I didn't know how I would compare them.
At the moment my query looks like this:
$topUser = DB::table('statistics')
->join('users', 'statistics.user_id', '=', 'users.id', 'inner')
->select('fname', 'user_id', DB::raw('sum(price) as total_collection'))
->groupBy('user_id')
->orderBy('total_collection','desc')
->get();
What I want to do, in pseudocode, is something along the lines of;
->where 'created_at' <= 30 days ago
Thanks in advance!
It's basically that simple.
->whereDate('created_at', '<=', \Carbon\Carbon::now()->subDays(30));
You can take advantage of mysql's date functions by using DB::raw
->where('created_at', '<=', DB::raw("DATE_SUB(CURDATE(),INTERVAL 30 DAY)")

Categories