mardi 27 octobre 2015

How to upload an image to a form with many to many relationships?

this is very similar to this question. I am using Laravel 5 and trying to add files(an image) to my database with a form. I have a form I use to add various data (title, description, image) to my Article class. An article also 'belongsToMany' categories and days (many to many r/ship). The code below allows me to upload my data but it adds three instances of the article! The first two instances have the correct photo path/name (photo.jpg). And the third instance adds a name like this to the db: /tmp/phphJIIY1. It adds to the pivot tables correctly.

I think it's this line of the 'store' function

        $article = Article::create($request->all());    

that is causing the problems, but I need that line or I get the error described in my last question.

How can I order/change this code so I can upload an image and add categories/days to my article? I have installed intervention\image but am not using it yet.

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

    $article = Article::create($request->all());      

    $categoriesId = $request->input('categoryList');

    $article->categories()->attach($categoriesId);

    $daysId = $request->input('dayList');

    $article->days()->attach($daysId);

    return redirect()->route('articles_path');

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire