File upload with image validation in laravel

Laravel

Posted on 03 Jun 15 by Vickey
  5922



Laravel provide very easy method to upload a file.So lets create a simple file upload system

Step 1: Create a action in your controller for upload a file (if you did not created it)

public function uploadImage(){

    $this->layout->content = View::make('users.uploadImage');
}

Step 2: Create a uploadImage.blade.php file /view/users/ directory and put the below code

@if($errors->any())
    {{ implode ('', $errors->all('<p><strong>:message</strong></p>'))}}
@endif
{{ Form::open(array('url'=>'/postupload','files' => true))}} 
<table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <th>Photo</th>
            <th> {{ Form::file('photo') }} </th>
        </tr>
        <tr>
            <th></th>
            <th>{{ Form::submit('Submit!',array('class' => 'btn')) }}</th>
        </tr>
</table>
{{ Form::close() }}

Now you form ready now need to create an action for post this form and upload file

Step 3: Create a action in your controller

public function postupload(){

    $userdata = array('image' => Input::get('photo'),);
     $rules = array('image' => 'image');  // validate file type image

     $validator = Validator::make($userdata, $rules);
     if($validator->fails())
    { 
        return Redirect::back()->withInput()->withErrors($validator);
    }
    else{

        $file = Input::file('photo');
        $destinationPath = 'uploads'; // give path of directory where you want to save your files
        $filename = Str::random(20) . '.' . Input::file('photo')->guessExtension();
        $upload_success = Input::file('photo')->move($destinationPath, $filename);
        return Redirect::to('success_page');
    }
}

for validation you can use this also

$rules['image'] = 'mimes:jpg,png,gif,svg,jpeg';

Step 4: Now open your routes.php file and add routes for these two action

Route::get('/uploadImage', 'UserController@uploadImage');

Route::post('/postupload', 'UserController@postupload');

Now you can upload your file


If this post help you reduce time to develop, you can help me to maintain this website :)
www.000webhost.com