为 foreach() Laravel 标签提供的参数无效

Invalid argument supplied for foreach() Laravel tags

我只是使用 laravel 中的多对多关系为我的博客制作标签系统。 现在我正在尝试添加多标签,但出现错误:

Invalid argument supplied for foreach()

这是我的控制器

public function blogpost(Request $request){
    $this->validate($request, [
        'title' => 'required|max:255|unique:blogs',
        'content' => 'required',
        'image' => 'image|required',
    ]);
    $blog = new blog;
    $blog->title = $request->title;
    $blog->content = $request->content;
    $blog->slug = str_slug($blog->title, '-');
    $blog->user_id = Auth::user()->id;
    $blog->published_at = $request->published_at;
    if($request->hasFile('image')) {
        $file = Input::file('image');
        //getting timestamp
        $timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
        $name = $timestamp. '-' .$file->getClientOriginalName();
        $file->move(public_path().'/images/blog/', $name);
        $blog->image = $name;
        $thumb = Image::make(public_path().'/images/blog/' . $name)->resize(640,420)->save(public_path().'/images/blog/thumb/' . $name, 90);
    }

    $blog_id = $blog->id;
    $tags = $request->tag;

    foreach ($tags as $tag) {
        $tag = tag::firstOrNew(['name' => $tag]);
        dd($tag);
    }

    return Redirect::back()->with('status', 'Post Success');
}

你应该做的是确保标签是数组,所以你应该像这样改进你的验证:

$this->validate($request, [
        'title' => 'required|max:255|unique:blogs',
        'content' => 'required',
        'image' => 'image|required',
        'tag' => 'array|required',
        'tag.*' => 'required|string',
    ]);

现在你不验证它,所以你不知道你在 tag 中有什么 - 它是简单的字符串还是空值或其他东西。