Skip to content

File Upload in Laravel

Reading Time: 2 minutes

file upload in laravel

This article is about the file upload in laravel

It can be done by using two files one in controller and another in view does the job.

First have to create a view file where user can upload files under(resources/views/upload.blade.php)

@extends('app')
@section('content')

@if (Session::has("message"))
{{ Session::get("message") }}
@endif

@endsection

Create a controller called uploads under app/Http/Controllers/UploadController.php which will validate the file uploaded and process it.

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Input;
use Validator;
use Request;
use Response;

class UploadController extends Controller {

public function index() {
return view('uploads');
}

public function uploadFiles() {

// GET ALL THE INPUT DATA , $_GET,$_POST,$_FILES.
$input = Input::all();

// VALIDATION RULES
$rules = array(
'file' => 'image|max:3000',
);

// PASS THE INPUT AND RULES INTO THE VALIDATOR
$validation = Validator::make($input, $rules);

// CHECK GIVEN DATA IS VALID OR NOT
if ($validation->fails()) {
return Redirect::to('/')->with('message', $validation->errors->first());
}

$file = array_get($input,'file');
// SET UPLOAD PATH
$destinationPath = 'uploads';
// GET THE FILE EXTENSION
$extension = $file->getClientOriginalExtension();
// RENAME THE UPLOAD WITH RANDOM NUMBER
$fileName = rand(11111, 99999) . '.' . $extension;
// MOVE THE UPLOADED FILES TO THE DESTINATION DIRECTORY
$upload_success = $file->move($destinationPath, $fileName);

// IF UPLOAD IS SUCCESSFUL SEND SUCCESS MESSAGE OTHERWISE SEND ERROR MESSAGE
if ($upload_success) {
return Redirect::to('/')->with('message', 'Image uploaded successfully');
}
}

}

Now finally dont forget to define your routes to make it work.

Route::get('/', 'UploadController@index');
Route::post('upload/add', 'UploadController@uploadFiles');

Make Sure you create a directory  public/uploads with 0777 permissions where script storing files.

Useful functions to remember:

  1. The getClientOriginalname() used to get the actual name of the file when it is uploaded.
  2. getFilename() used to get the temporary name of the file given to our file on its temporary location.
  3. getRealPath() used to get the current location of the uploaded file.
  4. getClientSize() used to get the size of the uploaded file in bytes.
  5. getClientExtension() used to get the extension of the uploaded file.
  6. move() used to move the uploaded file to target location.First parameter is target or destination ,second parameter is the name of the file.

Leave a Reply