Skip to content
Advertisement

Lravel 5.4 Update method and uploading files

I would like in the method update() to upload files to the server.

upload method:

    private function upload($request){
    if($request->hasFile('image')){
        $image = $request->file('image');
        $extension = $request->file('image')->getClientOriginalExtension();
        $generate_name = md5(uniqid(rand(), true));
        $file_name = $generate_name . '.' . $extension;
        $image->move(public_path() . '/post_image/', $file_name);
        return $file_name;
    }
}

update method:

    public function update(ArticleRequest $request, $id)
{
    $article = Article::FindOrFail($id);

    $file = $this->upload($request);
    $article->image = $file;

    $article->update($request->all());

    Session::flash('message', 'Wpis został edytowany!');

    return redirect('articles');
}

However, when I send the form error occurs.

enter image description here

But the same code with the upload () method store works very well.

    public function store(ArticleRequest $request)
{
    $article = new Article($request->all());

    $file = $this->upload($request);
    $article->image = $file;

    Auth::user()->articles()->save($article);
    Session::flash('message', 'Wpis został dodany!');
    return redirect('articles');
}

Advertisement

Answer

I’ve just got this issue and fixed it using Input::all instead of $request object, something like:

$data = Input::all();
if(isset($data['image'])) {
    ... // Do your thing
}

It seems like there is any issue with the request helper/class and the UploadedFile when you make PUT instead of pure POST

Cheers!!…

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement