How to upload images or other files with Laravel

Uploading files with Laravel is very simple, everything you need is already built in.

The view:


    echo Form::open_for_files('upload', 'POST');

    echo Form::label('file', 'File:');
    echo Form::file('image');

    echo Form::submit('Upload');

    echo Form::close();

Note that we used “open_for_files()” which generates the form with ‘enctype=”multipart/form-data”‘ needed to upload files.

The Controller

We process the form just like any other form, Laravel’s Validator library has validation options for files, for this tutorial we make use of “image” rule to specify that the file should be an image and “max:” which represents the max file size in kilobytes.

Another useful rule for files is “mimes:” which we use to check for specific extensions, e.g. “mimes:jpg, png”, for this tutorial will keep it simple.

If you need to access the file and it’s attributes use Input::file(). e.g. Input::file(‘picture.size’); To retrieve all items from $_FILES use Input::file().

For uploading we use Input::upload() method that takes 3 parameters: the name of the input, the path were to upload the file and the file name(with extension)

    /*
     * Validate
     */
    $rules = array(
        'image' => 'image|max:300'
    );

    $inputs = array(
        'image' => Input::file('image')
    );

    $validation = Validator::make($inputs, $rules);

    if( $validation->passes() )
    {

        //set the name of the file
        $filename = Input::file('image.name');

        //Upload the file
        Input::upload('image', 'public/uploads', $filename);

    }//if it validate

It’s that simple.
Note: This code only represents the uploading process and doesn’t handle situations like when for example the validation fails.

Advertisements

3 thoughts on “How to upload images or other files with Laravel

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s