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

时间:2017-09-01 18:58:35

标签: php laravel laravel-5 laravel-5.5

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

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

1 个答案:

答案 0 :(得分:1)

您应该做的是确保标记是数组,因此您应该像这样改进验证:

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

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