Ad

Image Uploading Laravel 5.2 : Trying To Get Property Of Non-object

I'm trying to upload an images using method moving the temporary files, and show it on my index page only with the path.

Here's the problem:

ErrorException in ProductController.php line 69: Trying to get property of non-object

In my controller that contain the line who error:

public function store(Request $request)
{
    $product=Request::all();
    Product::create($product);


    $imageName = $product->id_prod . '.' . 
        $request->file('images')->getClientOriginalExtension();

    $request->file('images')->move(
        base_path() . '/public/images/catalog/', $imageName
    );  

    return redirect('product');
}

And here's the database, the file has been uploaded on temp folder, but the file was fail to moved. I'm using Laravel 5.2, it was my first time to upload a files. And can someone explain to me why this one could be error.

Sorry for my bad grammars.

Images

Ad

Answer

You can try like this:

public function store(Request $request)
{
    $product = $request->all();

    $picture = '';

    if ($request->hasFile('images')) {
        $file = $request->file('images');
        $filename = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $picture = $product['id_prod'] . '.' . $extension;
        $destinationPath = base_path() . '/public/images/catalog/';
        $request->file('images')->move($destinationPath, $picture);
    }

    if (!empty($product['images'])) {
        $product['images'] = $picture;
    } else {
        unset($product['images']);
    }


    Product::create($product);

    return redirect('/product');
}
Ad
source: stackoverflow.com
Ad