Code: Select all
public function search(Request $request)
{
$query = $request->query('query');
$ingredients = explode(",", $query);
$ingredients = array_map('strtolower', $ingredients);
$ingredients = array_map('trim', $ingredients);
$ingredientIds = Ingredient::whereIn('name', $ingredients)->pluck('id');
$recipeIds = RecipeIngredient::whereIn('ingredient_id', $ingredientIds)->pluck('recipe_id');
$recipes = Recipe::whereIn('id', $recipeIds)->get();
return response()->json([
'ingredients' => $ingredients,
'recipes' => $recipes,
]);
}
Code: Select all
public function ingredients()
{
return $this->belongsToMany(Ingredient::class, 'recipes_ingredients', 'recipe_id', 'ingredient_id');
}
public function recipeIngredients()
{
return $this->hasMany(RecipeIngredient::class);
}
Code: Select all
protected $fillable = ['name'];
public function recipes()
{
return $this->belongsToMany(Recipe::class, 'recipes_ingredients', 'ingredient_id', 'recipe_id');
}
public function ingredientRecipes()
{
return $this->hasMany(RecipeIngredient::class);
}
Code: Select all
protected $table = 'recipes_ingredients';
public $timestamps = false;
public function recipe()
{
return $this->belongsTo(Recipe::class);
}
public function ingredient()
{
return $this->belongsTo(Ingredient::class);
}