Saturday, 5 November 2016

How to upload image in Laravel 5

Laravel the amazing framework of php which is most popular now.Today i want to share a post how to upload image in larvael 5.Laravel 5 provide very simple way to upload your image with validation like max size of 2MB, valid file extension like png,jpeg,gif,jpg or svg etc. You can easily implement in your application.

Laravel5


Step 1: You can make a simple route for uploading an image.Then first need to genreate view and second one is for post method.


Route::get('upload-image','ImageController@imageUpload');
Route::post('upload-image','ImageController@imageUploadPost');

Step 2: Now you need to create a controller named ImageController and create a images folder and check the permission of uploading an image. we will store the image in public/images folder.

app/Http/Controllers/ImageController.php


<?php

namespace App\Http\Controllers;

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

class ImageController extends Controller
{

    /**
    * Create view file
    */
    public function imageUpload()
    {
     return view('image-upload');
    }

    /**
    * Manage Post Request
    */
    public function imageUploadPost(Request $request)
    {
     $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

        $imageName = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('images'), $imageName);

     return back()
      ->with('success','Image Uploaded successfully.')
      ->with('path',$imageName);
    }

}

Step 3: Create a view file for uploading an image.


@if (count($errors) > 0)
<div class="alert alert-danger">
   <strong>Oops!</strong> There were some problems with your input.<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') }}">
@endif
<form action="{{ url('image-upload') }}" enctype="multipart/form-data" method="POST">
   {{ csrf_field() }}
   <div class="row">
      <div class="col-md-12">
         <input type="file" name="image" />
      </div>
      <div class="col-md-12">
         <button type="submit" class="btn btn-success">Upload</button>
      </div>
   </div>
</form>

Hope you like the post please comment below for the help.

Featured post

How to create dynamic schema in mongodb

Sometime what we need in our application is to create mongodb schema for collection and some of our collection schema are same but names are...

Popular Posts