Uploading files in Laravel 4

This is a super short post about uploading files with Laravel 4.

I have struggled a few minutes trying to convert this from L3 format to L4 and to save somebody time decided to post this short PHP script.

This script can work with multi file uploads that I have documented in my previous blog post on AJAX file uploads – https://maxoffsky.com/code-blog/howto-ajax-multiple-file-upload-in-laravel/ basically adapting that method to the new Laravel 4 file operations.

In your controller where you POSTing your file upload, insert the following code:

$file = Input::file('file');
$destinationPath = 'uploads';
// If the uploads fail due to file system, you can try doing public_path().'/uploads' 
$filename = str_random(12);
//$filename = $file->getClientOriginalName();
//$extension =$file->getClientOriginalExtension(); 
$upload_success = Input::file('file')->move($destinationPath, $filename);

if( $upload_success ) {
   return Response::json('success', 200);
} else {
   return Response::json('error', 400);
}

This will give your file a random filename and  save it in the uploads folder.

Enjoy!

UPDATE:

I wrote a lengthy chapter of a book about AJAX file uploads and included a server-side example built with Laravel. Check it out here: http://leanpub.com/frontend

Liked it? Take a second to support Maks Surguy on Patreon!
Become a patron at Patreon!

You may also like

46 comments

  • Juukie14 May 9, 2013  

    Thanks for sharing!

  • Osvaldo May 12, 2013  

    Hi there Max, I was looking for this 🙂
    What I actually want is to extend on it… Here’s the business logic of my project:

    1. When a user registers, a folder with their name is created on the server.

    2. When they upload files, the files will then be uploaded to their folder.

    Now my problem is: how do I use The SESSION variable to create the folder and upload the file? I’ve been in an adventure of trial and error lol.

    This sure shed some light into what I wanna do. But any help you can give is welcome. Thanks again, I always find your posts useful.

    Regards
    Osvaldo Manuel

  • Maks Surguy May 12, 2013  

    Why do you need to use the session variable?
    You can use the user’s folder (preferably you store the name of the folder as a random text string 10-16 characters long in the DB, for example in column named foldername) and upload the files into it like this :

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

    $destinationPath = 'uploads/'.Auth::user()->foldername;
    $filename = $file->getClientOriginalName();
    $upload_success = Input::file('file')->move($destinationPath, $filename);

    if( $upload_success ) {
    return Response::json('success', 200);
    } else {
    return Response::json('error', 400);
    }

    That’s pretty much it =)
    Of course you might want to make sure that the files don’t overwrite each other if they have the same file name. To do that you will need to add more things, you will need to give a random name to the file (str_random(12) but preserving extension with $extension =$file->getClientOriginalExtension();) when you are saving the file and also save file’s real name in the DB under column “alias”. Then you can do some magical things with that and your files will never overlap and won’t be rewritten.

    Hope this helps.
    Let me know if you have more questions.

  • Ru May 22, 2013  

    in my laravel app i’m trying to upload an image, this works, I save the image in /uploads/ but when I try to show it I can’t access to the folder, how can I do?

  • Maks Surguy May 22, 2013  

    what do you get? what errors?

  • Ru May 23, 2013  

    good afternoon, the problem is I do not know how to tell the view what is file path, my upload folder is in the root

  • Kapder July 10, 2013  

    How to show url which is image uploaded ?

    Thanks

  • kennedy August 7, 2013  

    This is very good tutorial. I would like to do the same but mine will be like user register to my site then all the registered user will access the download section where i will be having a list of file for download eg pdf, docx and even zip files. So how can implement the download part for only users using laravel 4. An example will be really nice or advice.

  • Maks Surguy August 7, 2013  

    You can check if the user has permissions to download the file (this will be up to you how you want to check that, probably in the controller or even in the model) and then you can use the following StackOverflow answer to initiate the download of large size files:
    http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel

  • kennedy September 21, 2013  

    Hi Mark.
    Thanks for this nice tutorial. By any chance do you have this project in github or have it somewhere we can get the source code for the entire project.

  • Maks Surguy September 21, 2013  

    I’m sorry I don’t have it up on Github yet but I am going to put a lot of my projects on Github soon, please subscribe to my blog so you know when it will be posted!

  • Riggs November 19, 2013  

    Sorry for digging out old post but I have problem with laravel 4 and dropzone. If i choose multiple file (for example 10 images) laravel uploads it in weird way – for example creates 10 files on server but it looks like only 2 images were uploaded couple of times.. Code is same as yours, i only resize uploaded and moved images.

  • aditiyagita November 21, 2013  

    thank’s for sharing mark, awesome !

  • Muhammed AK January 29, 2014  

    it shows success. but the file is not actually uploaded in that folder and no error showing

  • aditya menon March 20, 2014  

    Thanks for the useful post. May I ask why random folder instead of a random file name? Preserving the original name can be achieved by storing the value in a DB. Persistence is an inevitable requirement considering that even the random folder name needs to be remembered. I feel we are creating additional load on the filesystem with the random folder approach.

  • Maks Surguy March 20, 2014  

    Good notice, Aditya! I think the project I was doing at the time required separate folders for some of the uploads but overall of course it is better to have as few folders as possible and random filenames for files inside the folders. I’ll update the code to reflect that.

  • Gio April 9, 2014  

    Thanks a lot! One question, if I wanted to use a csrf token, for security, how would your approach be ?

  • Maks Surguy April 9, 2014  

    You would have to attach it as an additional form field. Also research a bit about CSRF with AJAX in Laravel.

  • kol April 29, 2014  

    Nice tut bro ! And what about pushing image name to database. is that possible ? I m newbie for laravel

  • Maks Surguy April 30, 2014  

    You would just save the filename to the database, not the whole file. I will be releasing a chapter of a book about this soon.

  • Vijay May 7, 2014  

    hi Maks, thanks for sharing this. i have a problem while using this as: TokenMismatchException, can you pls help me.?

  • Maks Surguy May 7, 2014  

    That has to deal with CSRF token. You might want to disable the CSRF token filter for the route that handles the file upload and it should work fine.

  • Simon May 9, 2014  

    Hi, How would you save the path of the image to the db? Also, how would you handle if you upload multiple files, then save each one to the db?

  • Maks Surguy May 17, 2014  

    Hello! I just store the path relative to the public folder and use “url(‘uploads/myfile.jpg’)” format to get the full URL of the file. The multiple file upload is just done by saving the path to each file into a separate row in the DB.

  • Joseph Rex June 16, 2014  

    This way it seems like you’re referring to one file. What if they are multiple files?

  • maxsurguy June 16, 2014  

    Parallel uploads is not something you would ever want to do on a website unless you have your own private server with a huge(or unlimited) amount of RAM. The best and most optimal way is to do sequential file uploads and most file uploading plugins allow you to do that.

  • Joseph Rex June 18, 2014  

    Thanks. Also, you should add public_path() to your $destinationPath like so public_path() . ‘/uploads’ . That gave me issue for a while till I figured it out

  • maxsurguy June 18, 2014  

    thanks! Will add that to the post as an “FYI”

  • dan avila June 27, 2014  

    This work whit ajax???

  • Dattz June 28, 2014  

    Yes it does.

  • Dattz June 28, 2014  

    Works like a charm. Thank you!

  • Yassine Ben Slimane July 1, 2014  

    sorry to say this but when I do the upload, only a few of the many uploads I make successed in uploading and the problem is that I don’t any errors to pinpoint if there is any problem !!

  • maxsurguy July 1, 2014  

    This means something is wrong with the server and how it handles PHP uploads…

  • David Holman August 28, 2014  

    WORKS LIKE A CHARM!
    Great work!

  • maxsurguy August 29, 2014  

    Thanks! Enjoy!

  • mark gxr January 8, 2015  

    cool. got basics from here and also found nice tutorial here http://tutsnare.com/upload-files-in-laravel/ and both makes my work easy. well done.

  • Manish Kumar Mishra April 9, 2015  

    An complete example of laravel file upload is given here . you can read about laravel file upload function reference from here http://www.tutsway.com/laravelfileupload.php.

  • Hossein shojaeyan July 16, 2015  

    for Laravel 5 ?

  • JulioJarrard May 23, 2016  

    Valuable comments . Talking of which , if one is wanting to merge two PDF files , my business partner encountered presentation here https://goo.gl/6542R3

  • Anwar Hamoude March 10, 2018  

    this is a waste of time- how about posting current information
    at the point when the information you’ve posted is obsolete you should have the sense to remove it

Leave a comment