In a form, I have a Tags field, which is a just a standard text field. A user can type a Tag name and it is added to the article.
I already have three tables: tags
, taggables
and articles
and they are linked via Eloquent relationship methods, given the setup in a previous question I asked.
This is my update method in my ArticleController
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$validatedData = $request->validate([
'title' => 'required',
'excerpt' => 'required',
]);
$article = Article::find($id);
$article->title = $request->get('title');
$article->author = $request->get('author');
$article->category = $request->get('category');
$article->excerpt = $request->get('excerpt');
$article->content = $request->get('content');
$article->featuredImage = $request->get('featuredImage');
$article->featuredVideo = $request->get('featuredVideo');
$article->readingTime = $request->get('readingTime');
$article->published = $request->get('published');
$article->save();
/**
* Once the article has been saved, we deal with the tag logic.
* Grab the tag or tags from the field, sync them with the article
*/
$tags = $request->get('tags');
$comma = ',';
if (!empty($tags)) {
if (strpos($tags, $comma) !== false) {
$tagList = explode(",", $tags);
// Loop through the tag array that we just created
foreach ($tagList as $tags) {
// Get any existing tags
$tag = Tag::where('name', '=', $tags)->first();
// If the tag exists, sync it, otherwise create it
if ($tag != null) {
$article->tags()->sync($tag->id);
} else {
$tag = new Tag();
$tag->name = $tags;
$tag->slug = str_slug($tags);
$tag->save();
$article->tags()->sync($tag->id);
}
}
} else {
// Only one tag
$tag = Tag::where('name', '=', $tags)->first();
if ($tag != null) {
$article->tags()->sync($tag->id);
} else {
$tag = new Tag();
$tag->name = $tags;
$tag->slug = str_slug($tags);
$tag->save();
$article->tags()->sync($tag->id);
}
}
}
return back();
return redirect()->back();
}
In the section of this method that looks for tags, I do the following things:
- Check if the field is not empty
- Check if the string sent contains a comma
- If there is a comma, I use
explode()
to convert the string into an array - Loop through the array to see if the given tag within the string already exists
- If it doesn't exist, I create it and then sync it with the Article, otherwise I just sync it
This approach feels very messy, however, is there any way I could make this cleaner?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire