Laravel File(Image) Upload Example with Validation
In this tutorial i want to share with you how to create image uploading in Laravel 5. If you are beginners then you can do that simply. Laravel 5 provide very simple way to create file uploading with proper validation like max file size 2mb, file extention should be jpeg,png,jpg,gif or svg etc. So you can easily also implement this on your laravel application. I give you very easy and simple example that way you can undestand very well. So let's start from routes define.
1. Define Route
First you have add two route in routes.php file. first one for generate view and second one for post method. so let's add bellow route in your routes.php file.
app/Http/routes.php
Route::group(['middleware' => 'web'], function () {
Route::get('fileUpload', function () {
return view('fileUpload');
});
Route::post('fileUpload', ['as'=>'fileUpload','uses'=>'HomeController@fileUpload']);
});
2. Add Controller Function
Ok, now we need to add fileUpload() in HomeController.php file. If you don't have HomeController then you can create new and put bellow code on that file.
app/Http/Controllers/HomeController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function fileUpload(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $input['imagename']);
$this->postImage->add($input);
return back()->with('success','Image Upload successful');
}
}
3. Add Blade File
In At Last we require to create view file for image or file uploading. so you can create fileUpload.blade.php and put following code in that file.
resources/views/fileUpload.blade.php
@extends('layouts.app')
@section('content')
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
{!! Form::open(array('route' => 'fileUpload','enctype' => 'multipart/form-data')) !!}
<div class="row cancel">
<div class="col-md-4">
{!! Form::file('image', array('class' => 'image')) !!}
</div>
<div class="col-md-4">
<button type="submit" class="btn btn-success">Create</button>
</div>
</div>
{!! Form::close() !!}
@endsection
Now you check....
Video

Hardik Savani
I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.