File Upload and storage in laravel 5

When Interacting with files, There may be several times we’d like users to upload files on our server like images, resume etc. So these few steps will show you how Laravel handles upload and store multiple files through forms. 

 

Step 1. Adding a route upload which redirect to fileUpload view page.

App/Http/routes.php

<?php
Route::get('upload', function(){
    return view('fileUpload');
});

 

Step 2. After redirect via route we have a simple form for just uploading the file. In Form::open() we have an attribute url for form redirection where further process will perform in 3rd step. Form open has an attribute 'files'=>true equivalent to enctype="multipart/form-data" in laravel which allow to user upload files.

resources/views/fileUpload.blade.php

<?php
@if(Session::has('success'))
    <h2>{!! Session::get('success') !!}</h2>
@endif
<div>Upload form</div>
{!! Form::open(array('url'=>'apply/multiple_upload','method'=>'POST', 'files'=>true)) !!}
// Multiple uploads are possible
{!! Form::file('images[]', array('multiple'=>true)) !!}
{!! Form::submit('Submit') !!}
{!! Form::close() !!}

 

Step 3. I am not using controller because trying to keep simplest as possible. $files getting all images files through input method.

Now, Running foreach loop which distinct each file and store into public/uploads folder. After all these process our request redirecting to upload route( step1 ) with success message.

App/Http/routes.php

<?php
Route::post('apply/multiple_upload', function(){
    $files = Input::file('images');
    foreach($files as $file) {
        $destinationPath = public_path() .'/uploads/';
        $filename = $file->getClientOriginalName();
        $file->move($destinationPath, $filename);
    }
    return Redirect::to('upload')->with('success', 'Upload successfully');
});

 

We have done our small Todo list with use of file method but File method has much more extended variety of methods for interacting with the file that may help you in your projects.

<?php

// Retrieving An Uploaded File
$file = Input::file('image');

// Determining If A File Was Uploaded
if (Input::hasFile('image'))
{
    //
}

// Determining If An Uploaded File Is Valid
if (Input::file('image')->isValid())
{
    //
}

// Moving An Uploaded File
Input::file('image')->move($destinationPath);
Input::file('image')->move($destinationPath, $fileName);

// Getting Requested file path
$path = Input::file('image')->getRealPath();

// Getting Original name of the file
$name = Input::file('image')->getClientOriginalName();

// Getting uploaded File extention
$extension = Input::file('image')->getClientOriginalExtension();

// Getting Size of the file
$size = Input::file('image')->getSize();

// Getting MIME Type of uploaded file
$mime = Input::file('image')->getMimeType();

 

Something to say? Tell us in comment section.