Save searchable tags before model save to ensure indexing

This commit is contained in:
Christopher C. Wells 2021-04-04 20:19:50 -07:00
parent 5f19cb44dd
commit 25d37d0c55
2 changed files with 13 additions and 13 deletions

View File

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

View File

@ -252,7 +252,16 @@ class RecipeController extends Controller
]);
try {
DB::transaction(function () use ($recipe, $input) {
DB::transaction(function () use ($input, $recipe, $request) {
// Sync tags before save (to ensure indexing).
$tags = $request->get('tags');
if (!empty($tags)) {
$recipe->syncTags(explode(',', $tags));
}
elseif ($recipe->tags->isNotEmpty()) {
$recipe->detachTags($recipe->tags);
}
$recipe->saveOrFail();
$this->updateIngredients($recipe, $input);
$this->updateIngredientSeparators($recipe, $input);
@ -263,15 +272,6 @@ class RecipeController extends Controller
return back()->withInput()->withErrors($e->getMessage());
}
// Sync tags.
$tags = $request->get('tags');
if (!empty($tags)) {
$recipe->syncTags(explode(',', $tags));
}
elseif ($recipe->tags->isNotEmpty()) {
$recipe->detachTags($recipe->tags);
}
// Handle recipe image.
if (!empty($input['image'])) {
/** @var \Illuminate\Http\UploadedFile $file */