this is very similar to this question . I am using Laravel 5 and trying to add files (image) to my database using a form. I have a form for adding various data (title, description, image) to the Article class. The article also belongs to the categories "daysToMany" and days (many to many r / ships). The code below allows me to upload my data, but it adds three copies of the article! The first two copies have the correct path / photo name (photo.jpg). And the third instance adds this name to db: / tmp / phphJIIY1. It correctly adds identifiers to pivot tables.
I think this line of the "store" function
$article = Article::create($request->all());
which causes problems, but do I need this line or am I getting the error described in my last question .
How can I order / modify this code so that I can upload an image and add categories / days to my article? I set the intervention \ image, but not yet using it.
public function create()
{
$categories = Category::lists('name', 'id');
$days = Day::lists('dayname', 'id');
return view('articles.create', compact('categories', 'days'));
}
public function store(ArticleRequest $request)
{
$image_name = $request->file('image')->getClientOriginalName();
$request->file('image')->move(base_path().'/public/images', $image_name);
$article = ($request->except(['image']));
$article['image'] = $image_name;
Article::create($article);
// ABOVE THIS LINE WORKS TOTALLY MYSELF (if I comment below, it works fine here, but I need many of mine to work on r / ship)
$article = Article::create($request->all());
// ADD THIS LINE ABOVE TO MAKE "categories ()" WORK.
$categoriesId = $request->input('categoryList');
$article->categories()->attach($categoriesId);
$daysId = $request->input('dayList');
$article->days()->attach($daysId);
return redirect()->route('articles_path');
}
source
share