Tuesday 20 February 2018

Image File Upload in Laravel with Validation



This is post covered How to Upload Image or File in Laravel with server side validation. If you are beginner in Laravel and if you want to learn how to upload file or image on public folder of laravel framework, then in this post you can learn step by step how to upload image with validation in Laravel. Because upload of media is required feature in any web application and if you have build your web application by using Laravel then you have come right place. Here we have discuss upload of image file with validation rules like we should have to select file because image is required, selected file must be an image, image extension must be .jpg, .jpeg, .png, .gif and image size not exceeds 2 MB. If this validation rules not follow then it will display particular validation error on web page and image will not be uploaded. If this validation rules successfully passed then it will upload image in public folder of Laravel directory.

For this first we have to download and installed Laravel framework, so for this we have write following command in command prompt. In command prompt you have to first run composer command then after you have to run this command because this framework use composer for manage it's dependency.


composer create-project --prefer-dist laravel/laravel student_crud


This command will make student_crud directory and in that it will download Laravel framework. After this we want to make one controller for upload image file. For this we have write following command.


php artisan make:controller UploadfileController








This command will make UploadfileController.php controller in app/Http/Controllers directory. Now we want to make one view file for upload image. So for this we have make upload.blade.php view file in resources/views directory and write following code.


<!DOCTYPE html>
<html>
 <head>
  <title>File Uploading in Laravel</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  
  <div class="container">
   <h3 align="center">File Uploading in Laravel</h3>
   <br />
   @if (count($errors) > 0)
    <div class="alert alert-danger">
     Upload Validation Error<br><br>
     <ul>
      @foreach ($errors->all() as $error)
       <li>{{ $error }}</li>
      @endforeach
     </ul>
    </div>
   @endif
   @if ($message = Session::get('success'))
   <div class="alert alert-success alert-block">
    <button type="button" class="close" data-dismiss="alert">×</button>
           <strong>{{ $message }}</strong>
   </div>
   <img src="/images/{{ Session::get('path') }}" width="300" />
   @endif
   <form method="post" action="{{url('/uploadfile')}}" enctype="multipart/form-data">
    {{ csrf_field() }}
    <div class="form-group">
     <table class="table">
      <tr>
       <td width="40%" align="right"><label>Select File for Upload</label></td>
       <td width="30"><input type="file" name="select_file" /></td>
       <td width="30%" align="left"><input type="submit" name="upload" class="btn btn-primary" value="Upload"></td>
      </tr>
      <tr>
       <td width="40%" align="right"></td>
       <td width="30"><span class="text-muted">jpg, png, gif</span></td>
       <td width="30%" align="left"></td>
      </tr>
     </table>
    </div>
   </form>
   <br />
  </div>
 </body>
</html>


After this we have write following code in UploadfileController.php this code will first load view file and in that file we can select file and it will send request to this controller again for upload image file with validation.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;

class UploadfileController extends Controller
{
    function index()
    {
     return view('upload');
    }

    function upload(Request $request)
    {
     $this->validate($request, [
      'select_file'  => 'required|image|mimes:jpg,png,gif|max:2048'
     ]);

     $image = $request->file('select_file');

     $new_name = rand() . '.' . $image->getClientOriginalExtension();

     $image->move(public_path('images'), $new_name);
     return back()->with('success', 'Image Uploaded Successfully')->with('path', $new_name);
    }
}
?>


Lastly, we want set route for two method of UploadfileController.php controller. For this we have to go to routes/web.php and in that we have write following code.


<?php

Route::get('/', function () {
    return view('welcome');
});

Route::get('/uploadfile', 'UploadfileController@index');
Route::post('/uploadfile', 'UploadfileController@upload');

?>


So, this whole code is for how to upload image file with validation in Laravel.

13 comments:

  1. como salvar a imagem no banco de dados

    ReplyDelete
  2. hello, please upload Project Database.
    p.s Thanks Weblesson

    ReplyDelete
  3. I'm not getting any error. But when i upload a valid image it shows error.
    and can you please tell me image will be save in images folder. Where we can find this folder.
    waiting for your kind reply.

    ReplyDelete
  4. Replies
    1. in public folder -> Image folder -> (image name is some random number with original extension)

      Delete
    2. The files goes to the public folder then in images folder

      Delete
    3. imagino que esta linea no te dice nada:
      $image->move(public_path('images'), $new_name);

      Delete
  5. required|image|mimes:jpg,png,gif|max:2048

    sir can u explain this?, image its colomn on database name or type of file?
    cause my project cant insert image, cause my database name its, avatar

    ReplyDelete