Francis Albert Calas
Francis Albert Calas

Reputation: 51

Why is my image not storing in a specified folder in Laravel 5.6?

In my form, I asked for an image to upload. Then I already validated it and it works. But the file is not stored in the uploads folder.

Here's a snippet of my ProductController:

public function store(Request $request)
{
    // Validate fields
    $this->validate($request, [
        'product_name' => 'required',
        'product_price' => 'required',
        'product_desc' => 'required',
        'product_img' => 'image|required'
    ]);

    // Upload image
    if($request->hasFile('image')) {
        app()->make('path.public/uploads');
        $image = $request->image;

        $image->move('uploads', $image->getClientOriginalName());


    }

    /*// Save the data into database
    Product::create([
        'name' => $request->product_name,
        'price' => $request->product_price,
        'description' => $request->product_desc,
        'image' => $request->image->getClientOriginalName()
    ]);


    // Echo a session message
    $request->session()->flash('msg', 'Your product has been added');


    // Redirect to view page
    return redirect('/products');*/

}

I already tried looking at other possible solutions but the other questions were already at storing the image in the database. I also tried checking if uploads was a directory and existed, and it is.

Can anyone please help? Thanks.

Upvotes: 1

Views: 2119

Answers (3)

Francis Albert Calas
Francis Albert Calas

Reputation: 51

I've already solved it. The variable was wrong all along. Instead of it being product_img, I placed image.

Here's the updated code:

    // Validate fields
    $this->validate($request, [
        'product_name' => 'required',
        'product_price' => 'required',
        'product_desc' => 'required',
        'product_img' => 'image|required'
    ]);

    // Upload image
    if($request->hasFile('product_img')) {
        $image = $request->product_img;         
        $image->move('uploads', $image->getClientOriginalName());   
    }  

Upvotes: 0

user8063037
user8063037

Reputation: 161

app()->make('path.public/uploads');

Upvotes: 0

Levente Berky
Levente Berky

Reputation: 56

Try this: official documentation: This is how it should look in your controller:

if($request->hasFile('image')) { $request->file('image')->store('uplodads/', 'public'); }

This would store the image in /storage/app/public/uploads by default. You can also change the public path in /config/filesystems.php. You can then access the file (if you linked the storage) with asset('storage/uploads'.$img_name).

Upvotes: 1

Related Questions