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

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

}
+4
source share
1 answer

, . . : , , :

    $file = Request::file('resume');
    $extension = $file->getClientOriginalExtension();
    Storage::disk('local')->put($file->getFilename().'.'.$extension,  File::get($file));
    $resume = new Resume();
    $resume->mime = $file->getClientMimeType();
    $resume->filename = $file->getFilename().'.'.$extension;
    //save resume & put candidate id as foreign key
    $candidate=new Candidate();
    $data=array_except($data, array('_token','resume'));
    //attach blank candidate to current user
    $user->candidate()->save($candidate);
    $candidate->resume()->save($resume);

    //find the right instance of candidate we want to update*
    $candidate=$user->candidate($user);
    //Now update the candidate with data once it been attached.
    $candidate->update($data);
+1

Source: https://habr.com/ru/post/1613426/


All Articles