简体   繁体   中英

Prevent saving empty strings to database

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);
    }
}

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:

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

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

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);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM