防止将空字符串保存到数据库

时间:2018-10-26 19:31:35

标签: php laravel

当前,我有一个输入,用户可以在其中输入标签并以逗号分隔。然后在后端将字符串分解,并将每个标签保存到数据库中。但是,如果我不写任何标签,则将名称为空字符串的标签保存到数据库中。我该如何避免呢?

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

2 个答案:

答案 0 :(得分:2)

Request对象具有一种检查值是否为空字符串的方法。像这样的东西可以正常工作:

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

foreach循环不会被传递给它的空数组所影响。


从文档中:

如果您想确定请求中是否存在一个值并且该值不为空,则可以使用`filled`方法:

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

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

答案 1 :(得分:1)

您可以检查$tagsRaw是否为空:

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