skip to Main Content

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


  1. 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.

    
    use AppModelsRecipe;
    
    // Function to generate combinations of recipes
    function generateCombinations($items, $n, $start = 0, $result = [], &$results = []) {
        if ($n === 0) {
            $results[] = $result;
            return;
        }
    
        for ($i = $start; $i < count($items); $i++) {
            $result[] = $items[$i];
            generateCombinations($items, $n - 1, $i + 1, $result, $results);
            array_pop($result);
        }
    }
    
    // Function to filter combinations by total calories
    function filterCombinationsByCalories($combinations, $dailyCalories) {
        return array_filter($combinations, function($combination) use ($dailyCalories) {
            $totalCalories = array_sum(array_column($combination, 'calories'));
            return $totalCalories <= $dailyCalories;
        });
    }
    
    // Function to get daily meal plan
    function getDailyMealPlan($dailyCalories) {
        $mealCategories = ['snacks', 'lunch', 'dinner'];
        $mealPlan = [];
    
        foreach ($mealCategories as $category) {
            $recipes = Recipe::where('category', $category)->get()->toArray();
    
            // Generate combinations of recipes for this meal category
            $combinations = [];
            generateCombinations($recipes, 1, 0, [], $combinations);
    
            // Filter combinations by total calories
            $filteredCombinations = filterCombinationsByCalories($combinations, $dailyCalories);
    
            // If there are no valid combinations, choose a single recipe with the highest calories
            if (empty($filteredCombinations)) {
                $selectedRecipe = Recipe::where('category', $category)->orderBy('calories', 'desc')->first();
                $mealPlan[$category] = $selectedRecipe;
            } else {
                // Randomly select a combination from the filtered combinations
                $selectedCombination = $filteredCombinations[array_rand($filteredCombinations)];
                $mealPlan[$category] = $selectedCombination;
            }
        }
    
        return $mealPlan;
    }
    
    // Example usage
    $dailyCalories = 1500;
    $mealPlan = getDailyMealPlan($dailyCalories);
    print_r($mealPlan);
    

    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.

    Login or Signup to reply.
  2. 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.

    $dailyCalories = 1500; //Calory limit threshold
    
    $snack = Recipe::where('category', 'snacks')
        ->where('calories', '<', $dailyCalories / 3) // divide by 3 for a rough estimate
        ->inRandomOrder()
        ->first();
    
    $remainingCalories = $dailyCalories - $snack->calories;
    
    $lunch = Recipe::where('category', 'lunch')
        ->where('calories', '<', $remainingCalories / 2) // Divide by 2 for a rough estimate
        ->inRandomOrder()
        ->first();
    $remainingCalories -= $lunch->calories;
    
    $dinner = Recipe::where('category', 'dinner')
        ->where('calories', '<', $remainingCalories)
        ->inRandomOrder()
        ->first();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search