2017-09-01 101 views
0

我只是使用laravel中的多對多關係爲我的博客製作標籤系統。 現在我想要添加多標籤,但其得到錯誤:爲foreach提供的無效參數()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'); 
} 
+0

顯示你的表格。你如何收集字段「標籤」? –

+0

'$ tags'不能是數組。用'dd'將其值清除以確認。 – ceejayoz

回答

1

你應該做的是確保什麼是標籤數組,所以你應該提高你的驗證樣所以:

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

現在不進行驗證,所以你不知道你有tag - 是簡單的字符串或空或別的東西。

+0

謝謝,我忘了添加數組 –

相關問題