Correct tag handling for search indexing

This commit is contained in:
Christopher C. Wells 2021-04-06 14:21:37 -07:00
parent 7ab9dd3711
commit 9b795a743b
4 changed files with 23 additions and 9 deletions

View File

@ -101,8 +101,9 @@ class FoodController extends Controller
}
}
// Sync tags before save (to ensure indexing).
$tags = $request->get('tags');
$food->fill($attributes)->save();
$tags = $request->get('tags', []);
if (!empty($tags)) {
$food->syncTags(explode(',', $tags));
}
@ -110,7 +111,8 @@ class FoodController extends Controller
$food->detachTags($food->tags);
}
$food->fill($attributes)->save();
// Refresh and index updated tags.
$food->fresh()->searchable();
session()->flash('message', "Food {$food->name} updated!");
return redirect()->route('foods.show', $food);

View File

@ -253,8 +253,12 @@ class RecipeController extends Controller
try {
DB::transaction(function () use ($input, $recipe, $request) {
// Sync tags before save (to ensure indexing).
$tags = $request->get('tags');
$recipe->saveOrFail();
$this->updateIngredients($recipe, $input);
$this->updateIngredientSeparators($recipe, $input);
$this->updateSteps($recipe, $input);
$tags = $request->get('tags', []);
if (!empty($tags)) {
$recipe->syncTags(explode(',', $tags));
}
@ -262,10 +266,8 @@ class RecipeController extends Controller
$recipe->detachTags($recipe->tags);
}
$recipe->saveOrFail();
$this->updateIngredients($recipe, $input);
$this->updateIngredientSeparators($recipe, $input);
$this->updateSteps($recipe, $input);
// Refresh and index updated tags.
$recipe->fresh()->searchable();
});
} catch (\Exception $e) {
DB::rollBack();

View File

@ -35,6 +35,14 @@ class FoodControllerTest extends HttpControllerTestCase
return 'food';
}
/**
* @inheritdoc
*/
protected function createInstance(): Food
{
return $this->factory()->hasTags(5)->create();
}
public function testCanAddFoodWithoutNutrients(): void
{
/** @var \App\Models\Food $food */

View File

@ -71,6 +71,7 @@ class RecipeControllerTest extends HttpControllerTestCase
'steps' => $this->createFormDataFromRecipeSteps(RecipeStep::factory()->count(6)->make()),
'separators' => $this->createFormDataFromRecipeSeparators(RecipeSeparator::factory()->count(2)->make()),
'image' => UploadedFile::fake()->image('recipe.jpg', 1600, 900),
'tags' => implode(',', $this->faker->words),
];
$store_url = action([$this->class(), 'store']);
@ -96,6 +97,7 @@ class RecipeControllerTest extends HttpControllerTestCase
'steps' => $this->createFormDataFromRecipeSteps($instance->steps),
'separators' => $this->createFormDataFromRecipeSeparators($instance->ingredientSeparators),
'image' => UploadedFile::fake()->image('recipe.jpg', 1600, 900),
'tags' => implode(',', $this->faker->words),
];
$put_url = action([$this->class(), 'update'], [$this->routeKey() => $instance]);