Support the ongoing development of Laravel.io →
Eloquent Architecture

Hi guys,

I'm wondering how to deal with this situation:

I have this structure:

Ingredients (basic list of ingredients)

  • id
  • name

Groceries (basic list of groceries)

  • id
  • name

Recipe (recipe which is made from ingredients and/or groceries)

  • id
  • name

Recipeables (pivot table)

  • id
  • recipe_id
  • recipeable_id
  • recipeable_type
  • order
  • value

recipeable is FQN to an ingredient or grocery

I have this panel:

panel

  • and after button click I want to attach the ingredient or the grocery to the recipe
  • at the end I have these table of attached ingredients or groceries, sorted by an order, all in one table:

table

I'm trying to figure out best code solution, here is what I have so far, but I still have little feeling, that there is a better solution.

// Service
class AddRecipeableToRecipeService
{

	/**
	 * @param Recipe $recipe
	 * @param RecipeableRequest $request
	 */
	public function add(Recipe $recipe, RecipeableRequest $request)
	{
		$recipeable = Helper::getRecipeableModel(
			$request->input('recipeable'),
			$request->input('type')
		);

		$value = (int) $request->input('value');
		$order = (int) $request->input('order');

		$attributes = compact('value', 'order');

		if ($recipeable->hasMacronutrients() === TRUE) {
			$attributes += $recipeable->ratio($value);
		}
 
		// type is "recipe" or "grocery"
		$recipe->{str_plural($request->input('type'))}()->attach($recipeable, $attributes);
	}
}


// Helper
class Helper
{

	/**
	 * @var string[]
	 */
	private static $model = [
		'ingredient' => Ingredient::class,
		'grocery'    => Grocery::class,
	];



	/**
	 * @param int $ID
	 * @param string $type
	 * @return Ingredient|Grocery
	 */
	public static function getRecipeableModel($ID, $type)
	{
		return app(self::$model[$type])->findOrFail($ID);
	}
}

// Remove example
DB::table('recipeables')->delete($id);

What do you think? I don't know, how to work with editing, I need pivot values and model too.

Thanks a lot

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.