I am doing requests when I want to get users with specific age. But I do not know how to get users from database. For example if user has 19 yo, I want users from age 12 - I get that user. If he has 20 - not. Can you help me with my code? Because it doesn't work.
Here's my code:
if ($request->has('age_from'))
{
$user = User::with('user_data')->whereHas('user_data', function($query) use ($request) {
$birth_date = Carbon::now()->subYears($request->age_from)->toDateString();
return $query->where('date_of_birth', '>=', $birth_date);
})->get();
}
You shouldn't need to format the Carbon object, Laravel and Carbon work seamlessly in database queries:
$user = User::with('user_data')->whereHas('user_data', function($query) use ($request) {
$query->where('date_of_birth', '>=', Carbon::now()->subYears($request->age_from));
})->get();
Related
I'm creating a simple reservation system and I need to check that car is available.
I'm gonna create a custom rule but I have following problems:
1. I need to pass an argument few values from form to passes method: date, time_form, time_to, car_id. The first and second question get excited because;
2. I'm not sure how and where to call that method in the controller if I have to use it in a few input's .
3. I suppose I need to create a query to check that car exist. In pure php I create query but I'm not sure that my "laravel" style query in god:
$result = Reservation::where(function ($query) use ($request) {
$query->whereBetween('time_from', [$request->input('time_from), $request->input('time_to')])
->orWhereBetween('time_to', [$request->input('time_from'), $request->input('time_to')]);
})->where(function ($query) use ($request) {$query
->whereBetween($request->input('time_from'), ['time_from','time_to'])
->orWhereBetween($request->input('time_to'), ['time_from','time_to']);
})
->where('date',$request->input('date'))
->where('car_id',$request->input('car_id'));
and pure php
$sql1 = "select * from reservation
where ('$time_from' BETWEEN time_from AND time_to or '$time_to' BETWEEN time_from AND time_to)
and (time_from BETWEEN '$time_from' AND '$time_to' or time_to BETWEEN '$time_from' AND '$time_to')
and car_id = '$car_id'";
I'm newbie in laravel so I am asking you for understanding. I'm asking for some advice. Maybe is some better way to do this.
You can try the code below:
$result = Reservation::query()
->where(function ($query) use ($request) {
return $query
->whereBetween('time_from', [$request->input('time_from'), $request->input('time_to')])
->orWhereBetween('time_to', [$request->input('time_from'), $request->input('time_to')]);
})
->where(function ($query) use ($request) {
return $query
->whereRaw($request->input('time_from') . ' BETWEEN time_from AND time_to')
->orWhereRaw($request->input('time_to') . ' BETWEEN time_from AND time_to');
})
->where('date', $request->input('date'))
->where('car_id', $request->input('car_id'));
I want to filter my query and return only if the user hasRole "Premium" and limit the result to 10.
Along with this query is a count of records which Conversion has and sort it in DESC order by total column.
Right now I have a working query that returns the count of Conversion and with a User but without user filter Role.
// Model Conversion belongs to User
// $from & $end uses Carbon::createDate()
// Current code
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
->whereBetween('created_at', [$from,$end])
->where('type','code')
->where('action','generate')
->whereNotNull('parent_id')
->with('user')
->groupBy('user_id')
->orderBy('total', 'DESC')
->take(10)
->get();
// current result
foreach ($query as $q) {
$q->user->name; // To access user's name
$q->total; // To access total count
}
// I tried this but no luck
$query = Conversion::select('user_id',DB::raw('COUNT(*) as total'))
->whereBetween('created_at', [$from,$end])
->where('type','code')
->where('action','generate')
->whereNotNull('parent_id')
->with('user', function($q) {
$q->hasRole('Premium');
})
->groupBy('user_id')
->orderBy('total', 'DESC')
->take(10)
->get();
You need to use whereHas instead of with, like this:
->whereHas('user', function ($query) {
$query->where('role','Premium');
})
Use the whereHas() instead of with(). Also, you can't use hasRole() if it's not a local scope:
->whereHas('user.roles', function($q) {
$q->where('name', 'Premium');
})
I am doing filter script. User write age_to and I get users with maximum age. The problem is that my in my users table is only full date of birth. How can I get all data? I think intval function is good but I do not know how to use it in mysql query.
$user = User::with('user_x')->whereHas('user_x', function($query) use ($request) {
$birth_date = Carbon::now()->subYears($request->age_to)->toDateString();
return $query->where('date_of_birth', '<=', $birth_date);
})->get();
Intval probably won't do what you want, but Carbon may. Since you're going for age, then use Carbon's date setters:
$birth_date = Carbon::now()->subYears($request->age_from)->toDateString(); // Sets the birth date to today's date minus the requested years
Then you can use it in your query:
$user = User::with('user_x')->whereHas('user_x', function($query) use ($birth_date) {
return $query->where('date_of_birth', '<=',$birth_date);
})->get();
I am building a website where i have a booking mechanism.
The user can book a hotel room for X days if the room is available.
I am using:
Laravel 5.4
MySql
The room is unavailable if:
It is already booked by another user
The admin has set it as unavailable
The room capacity is less or equal to the number of travellers
If have 3 tables to store those data:
Rent: Contains the booking infos, such as rentStartDate and rentEndDate (as DateTime) and other fields (userId, rentalId, ...)
Unavailabilities: When the admin set a room as unavailable, it's stored here. I have the fields unavailabilityStartDate, unavailabilityEndDate (as DateTime) and rentalId
Rentals: This table contain all the infos regarding the room (capacity ,name, location, ...)
I am struggling to build a Eloquent query to check if the room is available before processing the user payment. Here is what i have for now:
public function isAvailableAtDates($rentalId, $startDate, $endDate, $capacity) {
$from = min($startDate, $endDate);
$till = max($startDate, $endDate);
$result = DB::table('rentals')
->where([
['rentals.rentalId', '=', $rentalId],
['rentals.rentalCapacity', '>=', $capacity]
])
->whereNotIn('rentals.rentalId', function($query) use ($from, $till, $rentalId) {
$query->select('unavailabilities.rentalId')
->from('unavailabilities')
->where([
['unavailabilities.rentalId', '=', $rentalId],
['unavailabilityStartDate', '>=', $from],
['unavailabilityEndDate', '<=', $till],
]);
})
->whereNotIn('rentals.rentalId', function($query) use ($from, $till, $rentalId) {
$query->select('rent.rentalId')
->from('rent')
->where([
['rent.rentalId', '=', $rentalId],
['rentStartDate', '>=', $from],
['rentEndDate', '<=', $till]
]);
})
->select('rentals.rentalId')
->get();
return count($result) == 1;
}
Let's say I have a row inside Unavailabilities with:
unavailabilityStartDate = 2017-04-26 00:00:00
unavailabilityEndDate = 2017-04-30 00:00:00
When calling the method with some dates outside of the range stored in Unavailabilities, i'm getting the expected result. When calling it with the exact same dates, i'm getting no result (which is what i want).
So far so good!
The problem is if i'm calling it with a start date between 26 of April and 30th and a end date later in May, i am still getting a result even tho i shouldn't.
Could anyone help me with that?
This is not a laravel, nor a mysql issue.
try this:
->whereNotIn('rentals.rentalId', function($query) use ($from, $till, $rentalId) {
$query->select('unavailabilities.rentalId')
->from('unavailabilities')
->where([
['unavailabilities.rentalId', '=', $rentalId],
['unavailabilityStartDate', '<=', $till],
['unavailabilityEndDate', '>=', $from],
]);
})
->whereNotIn('rentals.rentalId', function($query) use ($from, $till, $rentalId) {
$query->select('rent.rentalId')
->from('rent')
->where([
['rent.rentalId', '=', $rentalId],
['rentStartDate', '<=', $till],
['rentEndDate', '>=', $from]
]);
})
You need all rent and unavailabilities records that had been started before $till and hadn't been ended before $from date.
Try to draw a time diagram.
I have two model User and Profile in one to one relationship.
I want to retrieve all user where profile.status == TRUE using following code.
$users = User::with(['profile' => function ($query) {
$query->where('status', TRUE);
}])->get();
dd(count($users)); //50
I have 50 users and only among of them only 3 has status == TRUE. But always it display 50.
You are getting 50 users because you are applying condition to profile. dd($user->profile) you will get only the records of the profile whose status is true.
Use whereHas():
$users = User::whereHas('profile', function ($query) {
$query->where('status', TRUE);
})->get();
dd(count($users));
If you want to make it work with single Query, you can use Query Builder join like
\DB::table('users')->join('profile', function ($join){
$join->on('users.id', '=', 'profile.user_id')->where('profile.status', '=',TRUE);
})->get();
You said you're having N+1 problem, so you need to use both whereHas() and with() like this to get users with profiles and to solve N+1 problem:
$users = User::whereHas('profile', function ($query) {
$query->where('status', TRUE);
})
->with('profile')
->get();