Laravel - Database query on default null date - laravel

I was trying to get some records of a table, which has a column 'UpdateDate' with default value NULL. I need to check if a record exists that either 'UpdateDate' is not today or 'UpdateDate' is NULL. The query I built is as follows:
DB::table('Users')
->where('id', '=', '10')
->where(function($query) {
$query->where('UpdateDate','<>',date("Y-m-d"))->orWhere('UpdateDate','is','NULL'); })
->exists()
It didn't work as expected. How should I modify it? Thanks.

Change you query to this
DB::table('Users')
->where('id', '=', '10')
->where(function($query) {
$query->where('UpdateDate','<>', date("Y-m-d"))
->orWhereNull('UpdateDate');
})
->exists();
If you have UpdateDate date as datatype.
If you have timestamp or datetime as datatype then change to this
DB::table('Users')
->where('id', '=', '10')
->where(function($query) {
$query->whereBetween('UpdateDate',[date("Y-m-d 00:00:00"), date("Y-m-d 23:59:59")])
->orWhereNull('UpdateDate');
})
->exists();

Related

Laravel 8 Carbon MM/DD/YYYY to Age compared inside join condition

Table: Search Preferences
Column: search_min_age (two digit number)
Table: Users
Column: birthdate (mm/dd/yyyy)
Both of these are joined together, but here is my error.
Could not parse 'users.birthdate': DateTime::__construct(): Failed to parse time string (users.birthdate) at position 0 (u): The timezone could not be found in the database
Here is snippet from my code:
$users = DB::table('users')
->join('search_preferences', function($q) {
$q->on('search_preferences.search_type', '=', 'users.account_type')
->on('search_preferences.search_identity', '=', 'users.account_identity')
->on('search_preferences.search_gender', '=', 'users.gender')
->on('search_preferences.search_tribe', '=', 'users.tribe')
->on('search_preferences.search_position', '=', 'users.position')
->on('search_preferences.search_min_age', '<=', Carbon::parse('users.birthdate')->age)
->on('search_preferences.search_max_age', '>=', Carbon::parse('users.birthdate')->age);
})
->where('users.verified_id', '=', 'yes')
->where('search_preferences.user_id', '=', auth()->user()->id)
->orderBy('users.id', 'ASC')
->select('users.*')
->paginate(9);

How to Filter Paid or Not Paid Student In laravel

I have just created some payment system for a school and I need to filter my data to Paid or Not Paid category.
$queryBuilder = Student::query()
->leftJoin('fee_scheem_maps', 'students.students_id', '=', 'fee_scheem_maps.sfc_student_id')
->leftJoin('fee_scheems', 'fee_scheem_maps.sfc_feescheem_id', '=', 'fee_scheems.fee_scheems_id')
->leftJoin('individual_fee_scheems', 'fee_scheem_maps.sifc_feescheem_id', '=', 'individual_fee_scheems.ifs_id')
->leftJoin('fee_groups', 'fee_scheems.fee_scheems_id', '=', 'fee_groups.fg_fee_scheem_id')
->leftJoin('school_fee_collectors', 'students.students_id', '=', 'school_fee_collectors.fc_student_id')
// ->Where('school_fee_collectors.fc_fee_group_id', $fromDate)
// ->orWhereNull('school_fee_collectors.fc_fee_group_id', $pstatus)
// ->orWhereNull('school_fee_collectors.fc_fee_group_id', $fromDate)
->when($fromDate, function ($query) use ($fromDate) {
return $query->where('school_fee_collectors.fc_fee_group_id', $fromDate);
})
->select('*', DB::raw('count(students_id) as total'));
It is working fine with one clause: I need to randomly choose where or notWhere in my case...
$queryBuilder = Student::query()
->leftJoin('fee_scheem_maps', 'students.students_id', '=', 'fee_scheem_maps.sfc_student_id')
->leftJoin('fee_scheems', 'fee_scheem_maps.sfc_feescheem_id', '=', 'fee_scheems.fee_scheems_id')
->leftJoin('individual_fee_scheems', 'fee_scheem_maps.sifc_feescheem_id', '=', 'individual_fee_scheems.ifs_id')
->leftJoin('fee_groups', 'fee_scheems.fee_scheems_id', '=', 'fee_groups.fg_fee_scheem_id')
->leftJoin('school_fee_collectors', 'students.students_id', '=', 'school_fee_collectors.fc_student_id')
->when($fromDate, function ($query) use ($fromDate) {
return $query->where('school_fee_collectors.fc_fee_group_id', $fromDate);
})
->where(function($query) use ($request){
if($request->paid_status){
$query->where('table_name.columName',$request->paid_status)
}
})->select('*', DB::raw('count(students_id) as total'));
you can use where like this , when your $request->paid_status is null means have no filter about paid not paid thats time query is return everything but when is have filter thats time only this where is working
->where(function($query) use ($request){
if($request->paid_status){
$query->where('table_name.columName',$request->paid_status)
}
})

using whereNotIn and subquery in query builder (Laravel 8)

I would like to make a controller function to search for users by name and display only those name that are not already in a project.
here is the SQL query to display users with name containing 'mmm' who are not already in project id = 2:
SELECT `firstname`
FROM `user_details`
WHERE (
`firstname` LIKE "%mmm%" AND `user_id` NOT IN (
SELECT `member_id` FROM `project_members` WHERE `project_members`.`project_id` = 2)
)
and in the query builder (which doesn't work):
$searchResults = DB::table('user_details')
->select('user_details.user_id', 'user_details.firstname', 'user_details.lastname', 'user_details.nickname', 'user_details.status')
->whereNotIn('user_details.user_id', DB::table('project_members')
->select('member_id')
->where('project_id', '=', $request->project_id)
->get()
->toarray()
)
->where('user_details.firstname', 'LIKE', '%'.$request->searchString.'%')
->orWhere('user_details.lastname', 'LIKE', '%'.$request->searchString.'%')
->get();
Do you know where I did wrong? Thank you!
Got it. I just needed ->pluck('member_id') instead of toarray()
And also, where/orWhere must be grouped.
$searchResults = DB::table('user_details')
->select('user_details.user_id', 'user_details.firstname', 'user_details.lastname', 'user_details.nickname', 'user_details.status')
->whereNotIn('user_details.user_id', DB::table('project_members')
->select('member_id')
->where('project_id', '=', $request->project_id)
->get()
->pluck('member_id')
)
->where(function ($query) use ($request) {
$query->where('user_details.firstname', 'LIKE', '%'.$request->searchString.'%')
->orWhere('user_details.lastname', 'LIKE', '%'.$request->searchString.'%')
->orWhere('user_details.nickname', 'LIKE', '%'.$request->searchString.'%');
})
->get();

Querying a database relationship with carbon in laravel

I'm trying to select the picture with the most likes from a category the previous day. However, my query returns a null result. My pictures are related to the likes through a has many polymorphic relationship.
Here is my query:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->whereDate('created_at', Carbon::yesterday());
})
->orderBy('likes_count', 'desc')
->with('user')
->first();
Here is my likeable relationship:
public function likes()
{
return $this->morphMany('App\Like', 'likeable');
}
Thank you for your help.
Try this:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->whereBetween('created_at', [Carbon\Carbon::yesterday()->startOfDay(), Carbon\Carbon::yesterday()->endOfDay()]);
})
->withCount('likes') // count yesterday's likes
->orderBy('likes_count', 'desc')
->with('user')
->first();
or this:
$foodOfTheDay = Picture::withCount('likes')
->where('picture_type', 'food')
->whereHas('likes', function($query) {
$query->where('created_at', '>=', Carbon::yeserday()->startOfDay())
->where('created_at', '<=', Carbon::yesterday()->endOfDay());
})
->withCount('likes') // count yesterday's likes
->orderBy('likes_count', 'desc')
->with('user')
->first();
Both of them should return picture with the highest likes the previous day (yesterday)
This query selects the picture with most likes without taking into consideration the other days' likes:
$foodOfTheDay = Picture::where('picture_type', 'food')->withCount(['likes' => function($query) {
$query->whereBetween('created_at', [Carbon::yesterday()-
>startOfDay(), Carbon::yesterday()->endOfDay()]);
}])
->orderBy('likes_count', 'asc')
->with('user')
->first();

Select unique records from child with condition on parent relationship

I have two tables, Shows and Episodes, each episode has show_id linking them one to many.
Now I need to get latest 6 episodes, one per show, where show.active is true
I've tried the following code:
$episodes = Episode::select(DB::raw('t.*'))
->from(DB::raw('(SELECT * FROM episodes ORDER BY id DESC) t'))
->whereHas('show', function($query) {
$query->where('active', '=', true);
})
->groupBy('t.show_id')
->take(6)
->get();
Unfortunately, I get the following:
Column not found: 1054 Unknown column 'episodes.show_id' in 'where clause' (SQL: select t.* from (SELECT * FROM episodes ORDER BY id DESC) t where exists (select * from shows where episodes.show_id = shows.id and active = 1) group by t.show_id limit 6)
I've also tried:
$episodes = Episode::where('active', true)
->orderBy('id', 'DESC')
->whereHas('show', function($query) {
$query->where('active', '=', true);
})
->groupBy('show_id')
->take(6)
->get();
It shows no error, but doesn't return latest of each show, groupBy gets the first record, I need the latest
This should work:
$episodes = Episode::where('active', true)
->whereHas('show', function($query) {
$query->where('active', '=', true);
})
->groupBy('show_id')
->orderBy('id', 'DESC')
->take(6)
->get();
You can try this
$episodes = Episode::selectRaw('max(id) as id, show_id')
->whereHas('show', function($query) {
$query->where('active', '=', true);
})
->orderBy('id', 'DESC')
->groupBy('show_id')
->take(6)
->get();
You can use a WHERE IN subquery:
$ids = Episode::selectRaw('max(id)')
->whereHas('show', function ($query) {
$query->where('active', '=', true);
})->groupBy('show_id');
$episodes = Episode::whereIn('id', $ids)
->take(6)
->get();

Resources