Moving File Uploads To Specific Folder With Laravel

- 1 answer

I am having issues getting my image uploads to move to the proper folders. When I upload them they just dump into the main img folder instead of going to the specific subfolder.

Here is the code I have:

            $rental = new Rental;

            $rental->title = $request->title;
            $rental->name = $request->name;
            $rental->description = $request->description;

             if ($request->hasFile('image')) {
                $image = $request->file('image');
                $filename = time() . '.' . $image->getClientOriginalExtension();
                $path = public_path('img/rentals' . $filename);

                 $rental->image = $filename;



You're missing a / in your $path. The following line...

$filename = time() . '.' . $image->getClientOriginalExtension();

will generate a string, something like 123456789.jpg. Then in the next line you're doing...

$path = public_path('img/rentals' . $filename);

which joins together img/rentals and 123456789.jpg, resulting in img/rentals123456789.jpg. Notice that . which concatenates two strings. You're then passing the resulting string to public_path which will refer to a folder in your public directory named img and a filename rentals123456789.jpg.

To solve your problem you just need to stick a forward slash in between:

$filename = time() . '.' . $image->getClientOriginalExtension();
$path = public_path('img/rentals/' . $filename);

which will result in a folder img/rentals inside your public path and a filename of 123456789.jpg.