In above video we will learn how to upload file like JPG,PNG,GIF etc by using laravel framework and also set validation before upload an image.
Step 1: Set file upload control in view file
<form role="form" name="gallery-form" id="gallery-form" method="post" action="{{ url('/admin/gallery-store') }}" enctype="multipart/form-data">
<input type="file" name="image" id="image">
<button type="submit" class="btn btn-primary pull-right"></button>
</form>
Step 2: Set route path
Route::post('/admin/gallery-store', 'Admin\GalleryController@store');
Step 3: Use below pre-define class
use Image;
use File;
Step 4: Use below function to set validations and file upload on server
public function store(Request $request)
{
//validation before insertion
$mime = $request->file('image')->getMimeType();//returns text/plain
$this->validate($request,
[
'image' => 'required|mimes:jpeg,jpg,png|max:10000'
],
[
'image.required' => 'Plese, select gallery image.',
'image.mimes' => 'The gallery image must be a file of type: jpeg, jpg, png.',
'image.max' => 'The image may not be greater than 10 mb.'
]
);
$image = $request->file('image');
//check image select or not
if(empty($image))
{
$imagename='';
}
else
{
$imagename = time().'.'.$image->getClientOriginalExtension();
$thumnailPath = public_path('/upload/gallery/thumnail/');
$orignalimagePath = public_path('/upload/gallery/');
/* ----------- check directory exist or not strat ------------ */
File::isDirectory($thumnailPath) or File::makeDirectory($thumnailPath, 0777, true, true);
/* ----------- check directory exist or not end ------------ */
//------- Genrate thumnail image
$thumnailImg=Image::make($image)->resize(600, null, function ($constraint) {
$constraint->aspectRatio();
});
$thumnailImg->save($thumnailPath.$imagename);
//------- Genrate orignal image
$orignalImg=Image::make($image)->resize(1200, null, function ($constraint) {
$constraint->aspectRatio();
});
$orignalImg->save($orignalimagePath.$imagename);
}