Laravel : Group users by month and output month name - laravel

I am querying users created in Laravel by month, here is my code
$devlist = DB::table("users")
->select("id" ,DB::raw("(COUNT(*)) as month"))
->orderBy('created_at')
->groupBy(DB::raw("MONTH(created_at)"))
->get();
This is giving me this
[{"id":1,"month":3},{"id":4,"month":4}]
How can I output the month as well instead of just the word month? So my expected result would be
[{"id":1,"january":3},{"id":4,"febuary":4}]

It's difficult to answer this without seeing the database, but I hope this will help:
$devlist = DB::table("users")
->select(DB::raw('EXTRACT(MONTH FROM created_at) AS month, COUNT(id) as id'))
->orderBy('created_at')
->groupBy(DB::raw('month'))
->get();

$statement = Purchase::selectRaw('monthname(purchase_date) month')
->groupBy('month')
->orderByRaw('min(purchase_date) asc')
->get();
echo "<pre>";
print_r($statement);
die;

Hard to tell without seeing your DB structure, but something like this would be fine. As noted, the output you are showing doesn't line up with the groupBy clause, but assuming the groupBy is correct, this will restructure the way you need:
$devlist = DB::table("users")
->select("id" ,DB::raw("(COUNT(*)) as month"))
->orderBy('created_at')
->groupBy(DB::raw("MONTH(created_at)"))
->get()
->map(function($monthItems, $month) {
return $monthItems->map(function($item) use ($month) {
return [
'id' => $item->id,
$month => $item->month,
];
});
});

Simply use this
\App\Model::selectRaw('monthname(date) as month, sum(total_amount) as total_sale')
->groupBy('month')
->orderByRaw('min(date) desc')
->get();

Related

Filter record through dates not working laravel

I have a expiry_date (type=date) column in my table
$currentDate = date('Y-m-d');
$Data = Post::whereDate('expiry_date','<=',$currentDate)->where(['status' => 'active'])->orWhere(['p_id' => 3])->select('id','title','status','p_id','expiry_date')->orderBy('id', 'DESC')->get();
i want to filter data if current date is greater than expiry date then those record should not be shown but in my scenario i'm still getting record.
Any solution Thanks.
You must group orWhere clause in closure. Grouping in closure is like () in real query.
$Data = Post::whereDate('expiry_date','<=',$currentDate)
->where(function($query){
return $query
->where(['status' => 'active'])
->orWhere(['p_id' => 3]);
})
->select('id','title','status','p_id','expiry_date')
->orderBy('id', 'DESC')
->get();
But, because I don't know your project - i may wrong with grouping.

Laravel Eloquent Relation Two Model

I have two model. User, Images. How can I get all the users who has images and the image date is between start and end date. Date column name "date".
You can try using Eloquent whereHas().
So the code should look like:
$users= User::whereHas('images', function($query) use ($start_date, $end_date) {
return $query->where([
['date', > , $start_date],
['date', < , $end_sate],
]);
})->get();
Document: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
Do not forget to format the date to however you want. Considering using whereDate()/whereBetween() is advised. Just play around till you get it right.
in controller class write a query to fetch all user with who has images and date is between the start and end date
$from = date('2018-01-01');
$to = date('2018-05-02');
$users= DB::table('users')
->join('images', 'users.is', '=', 'images.user_id')
->select('users.*')
->whereBetween('date', [$from , $to])
->distinct('users.id')
->get();

Laravel Eloquent whereTime() shows null

I have this query to get the events after the the current time and it shows as null. I think the whereTime condition is not working or I have a typo.
$query = Model::where('id', $request->id)
->where('status_id', 1)
->whereTime('event_date', '>=', Carbon::now())
->first();
When I don't have the whereTime condition and check the results, it shows this result
$query = Model::where('id', $request->id)
->where('status_id', 1)
// ->whereTime('event_date', '>=', Carbon::now())
->first();
dd(Carbon::now()->format('Y-m-d H:i:s'), $query->event_date);
Result
"2020-04-15 20:07:43"
"2020-05-23 18:00:00"
If your date like this "2021-03-21 13:33:52" then separate date and time like below
$date = Carbon::parse($timestamp)->format('Y-m-d');
$time = Carbon::parse($timestamp)->toTimeString();
Now you got date and time separated and write query to desire model like below:
User::where('status', 1)->whereDate('created_at', '>=', $date)
->whereTime('created_at', '>', $time)->get();
Hope this will help you. This works for me

Laravel eager loading & whereHas

Several questions have been asked about this but none provided a satisfactory explanation for this problem.
I run the following query:
$return = Vacation::whereHas('dates', function ($query) use ($from, $to) {
$query->whereBetween('start_date', [$from, $to]);
})->get();
According to the query log, this produces the following SQL. The returned result is correct but there is a problem with the JOINed data.
select * from `vacations` where exists (select * from `vacation_dates` where `vacations`.`id` = `vacation_dates`.`vacation_id` and `start_date` between '2017-08-01 00:00:00' and '2017-08-30 00:00:00')
Since there's no JOIN, the related records are added afterwards through eager loading and the constraint is lost.
The scenario involves Vacations that have multiple start / stop dates and I want to check which Vacations have a start_date within the $start and $end date range.
If there's no occurrences, no records are returned.
When there is an occurrence, the Vacation is returned with ALL the dates and not just the ones in the constraint.
I understand how / what it's doing but don't see how I can get what I need: the record with the joined data that follows the constraint.
Anyone?
Solution:
$callback = function($query) use($from, $to) {
$query->whereBetween('start_date', [$from, $to]);
};
$return = Vacation::whereHas('dates', $callback)->with(['dates' => $callback])->get();
Solution is from this SO post
Same answer as #stef gave, but better looking syntax (I believe)
$return = Vacation::query()
->whereHas('dates', $datesFilter = function($query) use ($from, $to) {
$query->whereBetween('start_date', [$from, $to]);
})
->with(['dates' => $datesFilter])
->get();

Laravel 5 - Check if date is today

I'm creating a timeline and I'm nearly finished. I want that the color of the date for each timeline event is the same beside if the date is "today".
So I need something like:
#if($event[$i]->created_at->format('d.m.Y') == *code or variable that says its today*)
....
#endif
But I couldn't figure out what I can do to save the todays date in a variable.. Does anybody knows a solution for this?
thanks!
You can use isToday() method to check if date is today:
if ($event[$i]->created_at->isToday())
you can use Carbon
#if($event[$i]->created_at->format('d.m.Y') == \Carbon::today() )
....
#endif
You can use
whereDate, whereMonth, whereDay, whereYear, whereTime
whereDate()
$users = DB::table('users')
->whereDate('created_at', '2019-11-31')
->get();
whereMonth()
$users = DB::table('users')
->whereMonth('created_at', '10')
->get();
whereDay()
$users = DB::table('users')
->whereDay('created_at', '20')
->get();
whereYear()
$users = DB::table('users')
->whereYear('created_at', '2019')
->get();
whereTime()
$users = DB::table('users')
->whereTime('created_at', '=', '11:20:45')
->get();

Resources