Home » Php » php – Laravel 4 file upload

php – Laravel 4 file upload

Posted by: admin July 12, 2020 Leave a comment


I’m trying to upload some photos and handle this with the build in Laravel functions. But I can’t for the life of me figure out how to do this properly. I have been able to actually upload something, but I’ve run into a few problems. This is the code I have right now:

If looked at the documentation, and found this function: $file = Input::file('photo'); I’ve used this function, and what the content of $file becomes is an instance of Symfony\Component\HttpFoundation\File\UploadedFile, which, as the documentation tells us, “extends the PHP SplFileInfo class and provides a variety of methods for interacting with the file.” http://laravel.com/docs/4.2/requests#files

Then I used this function Input::file('photo')->move($destinationPath); which should but the file in the desired folder on the server. And it did. But now comes the problem. Now all uploaded files have a filename like phpgoJnLc, and without an extension.

I’ve looked at the functions available from SplFileInfo and tried getExtension which give me an empty string and getFilename which also gives me something like phpgoJnLc.

Then I looked around on the internet and found a few part of code from Laravel 3, where they did something like this:

$filename = Str::random(20) .'.'. File::extension(Input::file('photo.name'));

But the result of this is give me only the result from Str::random(20) followed by a dot. Again, no file extension.

So, what am I doing wrong? How to upload a file with Laravel 4?

How to&Answers:

Looking in that same class file I see a getClientOriginalName() function…

$file = Input::file('photo');

… which ais ssuming you want to keep the original name your client sets… which could be hazardous, do some safety checks on it would be my advice. Getting the extensionname only is done with ->getClientOriginalExtension(), so you could also only save that part & add a random string before that in the second argument of the move() function.


This worked for me, especially when you want to change the name of the uploaded image:

$filename = 'New_Name'.'.'.Input::file('photo')->getClientOriginalExtension();


You can also generate a name for the file with the original file extension like so:

$filename = Str::random(20) . '.' . Input::file('image')->guessExtension();

if you try to use the following in Laravel 4:

$filename = Str::random(20) .'.'. File::extension(Input::file('photo.name'));

you will get this error:

'Call to undefined method Illuminate\Filesystem\Filesystem::guessExtension()'