I`m having trouble with an Eloquent query.
The structure of my Model is:
Coupon (for get discounts for a booking):
period_start (coupon is valid for some specific periods)
period_end (this end date, for example: the coupon is valid when you make a booking between 2018-02-01 and 2018-03-03)
booking_start (the period of when the booking is done)
booking_end (you can book for example from 2018-01-15 till 2018-01-30 only for the coupon to be valid)
Code:
$coupon = Coupon::where('period_start', '<=', $request->get('from_date'))
->where('period_end', '<=', $request->get('to_date'))
->where('booking_start', '<=', now()->format('Y-m-d'))
->where('booking_end', '>=', now()->format('Y-m-d'))
->first();
In the order field people pick two dates from a datepicker, thats where the request()'s are for.
This should work, but I don't get any results...
What about using dateBetween?
$start = Carbon::parse($request->start)->startOfDay(); //2016-09-29 00:00:00.000000
$end = Carbon::parse($request->end)->endOfDay(); //2016-09-29 23:59:59.000000
$clicks->dateBetween($start, $end);
https://laracasts.com/discuss/channels/eloquent/daterange-with-wherebetween
You should re format the date that get from the datepicker before query part, like this.
$date=date('Y-m-d', strtotime(str_replace('-', '/', $request->to_date)));
Related
i need to get payments where the payment date is done before 100 days ago, I have a (date) when make a payment, and i tried this, but doesn't working:
$statusSearch = Payment::where('date', '<', strtotime('-10 Days'))->get();
You can use Carbon subDays() like below:
$statusSearch = Payment::where('date', '<=', Carbon::now()->subDays(10)->toDateTimeString())->get();
Let's use whereDate, because we need to compare dates, and Carbon to have DateInterval:
$tenDaysAgo = Carbon::now()->subDays(10);
$statusSearch = Payment::whereDate('date', '<', $tenDaysAgo)->get();
Then, don't forget to go in the Payment model and cast date column to date:
protected $casts = [
'date' => 'date',
];
Also I suggest you to rename this column to something else, just to now have issue in the near future during the query.
I have so far came up with this query:
Order::select(DB::raw('sum(price) as sums'),
DB::raw("DATE_FORMAT(created_at,'%e') as day")
)
->where('seller_id', Auth::user()->id)
->whereBetween('created_at', [Carbon::now()->startOfMonth()
->subMonth(),Carbon::now()->endOfMonth()->subMonth()])
->orderBy('created_at', 'asc')
->groupBy('day')
->get();
This returns an array like this:
[{"sums":145867,"day":"3"},{"sums":19567,"day":"28"}]
This is almost what I need. I would now like to include even the name of the month in these results, like this:
[{"June" : {{"sums":145867,"day":"3"},{"sums":19567,"day":"28"}}}]
Simple, add month to your select and use collection method mapToGroups
If you don't want to see month number in result array - format result array in callback
...
DB::raw("DATE_FORMAT(created_at,'%c') as month")
...
->get()
->mapToGroups(function ($item, $key) {
return [Carbon\Carbon::create()->month($item['month'])->format('M') => $item];
});
Also you can use DATE_FORMAT(created_at,'%b') for month name from MySQL and don't use Carbon in callback, but, in my opinion, it's not good for possible localization. But this way more performance effective
In my my laravel 5.7.3 application , I need to get grouped date like
$voteItemUsersResults = VoteItemUsersResult::orderBy('created_at', 'desc')
->groupBy('created_at')
->having('created_at', '>', '2018-09-01')
->get();
but I need to get only day part of created_at, without time.
Which is the valid way to make it ?
Grouped by Only Day of Datetime .
$voteItemUsersResults = VoteItemUsersResult::orderBy('created_at', 'desc')
->groupBy(DB::raw('DATE_FORMAT(created_at, "%d")'))
->having('created_at', '>', '2018-09-01')
->get();
I have users and habits, and a habit_user table to join them.
I am querying like this:
$track = $h->userAnswers()->where('user_id', Auth::user()->id)->wherePivot('created_at', '=', Carbon\Carbon::now()->subDays($i))->first();
This is running in a loop that is counting back for 7 days. there is a record in the db that is created_at: 2018-10-23 04:48:44
In my habit model I have the method you'd expect:
public function userAnswers()
{
return $this->belongsToMany('App\Habit', 'habit_user_answers')->withTimestamps()->withPivot('answer_one', 'created_at')->orderBy('pivot_created_at', 'desc');
}
Why won't query get a record?
You are comparing the date time so only if both date and time is same, the query will throw a result.
You can compare dates like so:
wherePivot('created_at', '>=', Carbon\Carbon::now()->subDays($i)->startOfDay())->wherePivot('created_at', '<=', Carbon\Carbon::now()->subDays($i)->endOfDay())
First, I think you need to consider Laravel conventions about naming methods and properties.
I'll assume the following based on your structure that includes users and habits. So, we have a User model and a Habit model, a user belongsToMany habits and a habit belongsToMany users. Also the pivot table habit_user contains extra fields like answer_one, answer_created_at and timestamps.
If you want now to query the habits now you have two solutions:
1- using wherePivot()
auth()->user()->habits()->wherePivot('answer_created_at', today())->get();
auth()->user()->habits()->wherePivot('answer_one', '!=', 'something')->get();
2- using whereHas()
auth()->user()->whereHas('habits', function($query){
$query->where('pivot.answer_one', 'something');
})->get();
I want to return all of the rows in my database table that are a day or less old. I'm using Laravel 4. This is what I tried:
$date = date('Y-m-d H:i:s');
return MainContact::where(DATEDIFF('timestamp', $date), '<=', 1)->get();
This doesn't work. I read the documentation and it doesn't seem like you can pass Laravel MySQL functions. timestamp is a datetime field. How can I compare these dates in Laravel 4?
The answer that user1977808 gave you is not good because MySQL can't use an index on the timestamp column, since it has to compute an output of the DATE_SUB function for every row. Avoid such queries, they have to process the entire table every time!
How about something like this:
return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();
I put the >= in there because you said "a day or less old", so they must have timestamp that is later than yesterday.
Alternatively,
You can use Carbon API that bundle with Laravel.
ModelName::where( 'timestamp', '>=', Carbon::now() )->get();
Reference: http://laravel.com/docs/5.1/eloquent-mutators
You could also use whereDate(), whereDay(), whereMonth() and whereYear(). In this case, whereDate() could be used as such, with Carbon's easy date functions:
return MainContact::whereDate('dateField', '<', Carbon::now()->subDay())->get();
return MainContact::where('timestamp', '>=', time() - (24*60*60))->get();
You can also do a raw query by using:
$results = DB::query( 'query' );
You only don't the the model object back in the results var