I am receiving inputs for ‘make’, ‘model’, ‘fromyear’, and ‘toyear’ from the user. I want to prevent the user from entering a ‘fromyear’ and ‘toyear’ range that already exists in the database for the given ‘make’ and ‘model’.
For example, if there is a record in the database with ‘make’ as ‘Toyota’, ‘model’ as ‘Camry’, ‘fromyear’ as 2015, and ‘toyear’ as 2020, then the user should not be allowed to enter the following ranges:
- 2016 to 2017
- 2016 to 2018
- 2019 to 2022
- 2013 to 2016
However, if the ‘fromyear’ and ‘toyear’ do not fall within any existing range in the database, then the user should be allowed to enter them.
The database table has columns named ‘make’, ‘model’, ‘fromyear’, and ‘toyear’.
$has_range = PartsList::where('make', $request->make)
->where('model', $request->model)
->where(function ($query) use ($request) {
$query->whereBetween('fromyear', [$request->fromyear, $request->toyear])
->orWhereBetween('toyear', [$request->fromyear, $request->toyear]);
})
->exists();
if ($has_range) {
$msg = 'year range already exists for this make and model';
}
2
Answers
You can use the
where
andorWhere
methods in combination with thewhereBetween
method to check if a record exists with the given make, model, and year range. ThewhereBetween
method checks if a column’s value is between two values.To ensure that any kind of overlap is caught, you need to adjust your logic to consider all possible overlap scenarios:
Here’s how you can adjust your query to cover all these cases: