Eloquent: get only the date from timestamp - php

I want to get all the entries of a specific day for a user.. I don't know how to format the query.
public function getEntry()
{
$entries = Journal::where('id', '=', Auth::id())
->where('created_at', '=', '\Carbon\Carbon::now()->format("l j F Y")')
->get()->first();
return view('home')->with(compact('entries'));
}
I do not know how to format that 'created_at' to match the server time. Any help will be largely appreciated. Thank You.

Use whereDate() to get all entries for the specific day:
->whereDate('created_at', Carbon::today());
Or use whereBetween():
->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])
Or simple where():
->where('created_at', '>', Carbon::now()->startOfDay())
->where('created_at', '<', Carbon::now()->endOfDay())

Related

How to find if dates not found in table

$gno = head::select('point','DATE')
->where('DATE', '>', Carbon::now()->subDays(7))
->orderBy('DATE','desc')
->get();
This code I have used to get past seven days of records from current date but if the date is not found in the table I want to return 0.
I don't know how to achieve this, any help?
You can change your query to use exists.
$gno = head::select('point','DATE')
->where('DATE', '>', Carbon::now()->subDays(7))
->orderByDesc('DATE')
->exists();
This way you get either true or false.
If you want to get the records and return them if found or return 0 if there are none, you have to do this:
$gno = head::select('point','DATE')
->where('DATE', '>', Carbon::now()->subDays(7))
->orderByDesc('DATE')
->get();
return $gno->isNotEmpty() ? $gno : 0;
You need to generate each date in PHP and then go through it and get all items for that date:
$gno = head::select('point','DATE')
->where('DATE', '>', Carbon::now()->subDays(7))
->orderBy('DATE','desc')
->get();
$dates = collect(range(0,7))->mapWithKeys(function ($i) use ($gno) {
$date = Carbon::now()->subDays($i);
return [ $date->toDateString() => $gno->filter(function ($head) use ($date) {
return $date->isSameDay($head->DATE);
}) ];
});
This should return a collection with dates as keys and a collection of rows as values with the collection being empty if there are no items for that date.

Laravel: where not expired?

I have a column called expires_at and its a datetime in my MySQL database. I need to fetch records where expires_at hasn't been met, how can I do this?
My current query looks like this
Model::where('user_id', Auth::user()->id)->get();
You can also try this.
use Carbon\Carbon;
use App\Model;
$now = Carbon::now();
Model::where('user_id', Auth::user()->id)
->where('expired_at', '>', $now)
->get();
https://laravel.com/docs/5.6/queries#where-clauses
If you're looking to compare with current date, try:
Model::where('user_id', Auth::user()->id)
->whereDate('expired_at', '>', date('Y-m-d H:i:s'))
->get();

Laravel change date format in where clause to match Carbon::now()

I need to select entries based on dates happening in the future and the
entries contain the date format:
12/30/17
I'm trying to format the date and compare to Carbon::now() timestamp, with no luck.
$now = \Carbon\Carbon::now();
$bookings = DB::table('booking')
->select('booking.*')
->where('booking.uid', '=', Auth::id())
->where(DB::raw("(DATE_FORMAT(booking.date,'%Y-%m-%d 00:00:00'))"), ">=", $now)
->get();
You'll need to use STR_TO_DATE to convert the string.
$bookings = DB::table('booking')
->select('booking.*')
->where('booking.uid', '=', Auth::id())
->where(DB::raw("(STR_TO_DATE(booking.date,'%m/%d/%y'))"), ">=", $now)
->get();
STR_TO_DATE will convert 12/30/17 to 2017-12-30
I don't think you really need to check date format. Also, you have some redundand stuff in the query. Just do this:
Booking::where('uid', auth()->id())->where('date', '>=', now())->get();
And if the date format is really different in some of the rows in the same column, you really need to fix this and instead of making some dirty fix for that.
$bookings = DB::table('booking')
->select('booking.*')
->where('booking.uid', '=', Auth::id())
->where(DB::raw("(DATE_FORMAT(booking.date,'%Y-%m-%d'))"), ">=", $now)
->get();

eloquent query condition based on relation

Results(game_id, score)
Games(start, end, threshold)
Given a timestamp:
I want to find all results that belong to a game with a start & end time containing the timestamp time and where the result score is above the game threshold.
I have already managed to query for the time condition, but how can I additionally query for Results.score > games.threshold?
Results::whereHas('game', function($q) use ($timestamp) {
$q->where('start', '<=', $timestamp)
->where('end', '>=', $timestamp)
})->with('game')->get()
Try to use whereRaw inside whereHas and check if it works:
Results::whereHas('game', function($q) use ($timestamp) {
$q->where('start', '<=', $timestamp)
->where('end', '>=', $timestamp)
->whereRaw('results.score > games.threshold');
})->with('game')->get();

Laravel $q->where() between dates

I am trying to get my cron to only get Projects that are due to recur/renew in the next 7 days to send out reminder emails. I've just found out my logic doesn't quite work.
I currently have the query:
$projects = Project::where(function($q){
$q->where('recur_at', '>', date("Y-m-d H:i:s", time() - 604800));
$q->where('status', '<', 5);
$q->where('recur_cancelled', '=', 0);
});
However, I realized what I need to do is something like:
Psudo SQL:
SELECT * FROM projects WHERE recur_at > recur_at - '7 days' AND /* Other status + recurr_cancelled stuff) */
How would I do this in Laravel 4, and using the DATETIME datatype, I've only done this sort of thing using timestamps.
Update:
Managed to solve this after using the following code, Stackoverflow also helps when you can pull bits of code and look at them out of context.
$projects = Project::where(function($q){
$q->where(DB::raw('recur_at BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()'));
$q->where('status', '<', 5);
$q->where('recur_cancelled', '=', 0);
});
Updated Question: Is there better way to do this in Laravel/Eloquent?
Update 2:
The first resolution ended up not been right after further testing, I have now resolved and tested the following solution:
$projects = Project::where(function($q){
$q->where('recur_at', '<=', Carbon::now()->addWeek());
$q->where('recur_at', '!=', "0000-00-00 00:00:00");
$q->where('status', '<', 5);
$q->where('recur_cancelled', '=', 0);
});
You can chain your wheres directly, without function(q). There's also a nice date handling package in laravel, called Carbon. So you could do something like:
$projects = Project::where('recur_at', '>', Carbon::now())
->where('recur_at', '<', Carbon::now()->addWeek())
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.
EDIT:
As Joel said, you could do:
$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
Didn't wan to mess with carbon. So here's my solution
$start = new \DateTime('now');
$start->modify('first day of this month');
$end = new \DateTime('now');
$end->modify('last day of this month');
$new_releases = Game::whereBetween('release', array($start, $end))->get();
#Tom : Instead of using 'now' or 'addWeek' if we provide date in following format, it does not give correct records
$projects = Project::whereBetween('recur_at', array(new DateTime('2015-10-16'), new DateTime('2015-10-23')))
->where('status', '<', 5)
->where('recur_cancelled', '=', 0)
->get();
it gives records having date form 2015-10-16 to less than 2015-10-23.
If value of recur_at is 2015-10-23 00:00:00 then only it shows that record
else if it is 2015-10-23 12:00:45 then it is not shown.
Edited: Kindly note that whereBetween('date',$start_date,$end_date) is inclusive of the first date.

Categories