0

Currently I have an input in which the user is meant to write tags and separate them with commas. Then on the back-end the string is exploded and each tag is saved into the database. However, if I don't write any tags, a tag with name of empty string is saved into the database. How can I avoid that?

HTML

<div class="form-group">
    <label class='label' for="artwork-tags">Tags</label>
    <input class='input' type="text" name="artwork-tags" placeholder="Tags" value='{{ Request::old('artwork-tags') }}'>
    @include('partials.invalid', ['field' => 'artwork-tags'])
</div>

PHP

$tagsRaw = $request->input('artwork-tags');
$tags = explode(',', $tagsRaw);

foreach($tags as $tagName) {
    $tagExists = Tag::where('name', $tagName)->exists();
    if (!$tagExists) {
        $tag = new Tag();
        $tag->name = $tagName;
        $tag->save();
        $image->tags()->attach($tag);
    } else {
        $existingTag = Tag::where('name', $tagName)->first();
        $image->tags()->attach($existingTag);
    }
}
3
  • 1
    Check if $tagsRaw is not empty. Commented Oct 26, 2018 at 19:33
  • 1
    Simplier would be to add call to array_filter($tags) after exploding it and assign it’s results back to $tags. Commented Oct 26, 2018 at 20:24
  • The best is to declare you table's column as not null Commented Oct 26, 2018 at 21:15

2 Answers 2

2

The Request object has a way to check if a value is an empty string or not. Something like this will work fine:

$tags = $request->filled("artwork-tags") ? explode(',', $request->input("artwork-tags")) : [];

The foreach loop won't get touched with an empty array passed to it.


From the documentation:

If you would like to determine if a value is present on the request and is not empty, you may use the `filled` method:

    if ($request->filled('name')) {
       //
    }

https://laravel.com/docs/5.6/requests#retrieving-input

Sign up to request clarification or add additional context in comments.

Comments

1

You can check if $tagsRaw is not empty:

if( ! empty($tagsRaw = $request->input('artwork-tags')))
{
    $tags = explode(',', $tagsRaw);
    foreach($tags as $tagName) {
        $tagExists = Tag::where('name', $tagName)->exists();
        if (!$tagExists) {
            $tag = new Tag();
            $tag->name = $tagName;
            $tag->save();
            $image->tags()->attach($tag);
        } else {
            $existingTag = Tag::where('name', $tagName)->first();
            $image->tags()->attach($existingTag);
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.