I’m building a diet plan with Laravel 8.
Database looks like this:
Recipes | Category | Calories |
---|---|---|
Apple pie | snacks | 289 |
Banana pie | snacks | 386 |
Tomato Pasta | lunch | 712 |
Chicken Salad | lunch | 756 |
Vegetables soup | dinner | 410 |
Fish with potatoes | dinner | 652 |
I’d like to display the day’s meals according to daily calories.
For example, if my daily calories is 1500kcal, I want to get 3 recipes (lunch/dinner/snacks) for the day whose total calories do not exceed 1500kcal.
I know I can display a meal that does not exceed a certain calorie count:
$recipes = Recipe::where('category', 'snacks')
->where('calories', '<', '300')
->get()
;
But how to get randomly 3 different meals from various Categories who don’t exceed 1500kcal?
I hope I’ve made myself clear
2
Answers
Retrieve all recipes for each meal category (snacks, lunch, dinner).
Calculate all possible combinations of recipes for each meal category.
Filter combinations where the total calories do not exceed the daily calorie limit.
Select one combination from each meal category to form a daily meal plan.
This code will generate a daily meal plan with recipes from each meal category (snacks, lunch, dinner) where the total calories do not exceed the specified daily calorie limit. If there are no valid combinations for a meal category, it selects a single recipe with the highest calories for that category.
You should first give a threshold to your daily calories, and then when the query finds the random recipe, you should decrease the calories remaining by the number of the calories that this recipe has. Do this for each category.