Skip to content

How to upload files in Laravel 5

Uploading files in Laravel very easy ,You just need to create two routes one is for form view another one is for request processing(uploading files to the server), and one controller and view. Lets do it.

Create a view file where user can upload files(resources/views/uploads.blade.php) :

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

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

Create a controller called Uploads(app/Http/Controllers/UploadController.php), which will validate and process the uploaded files.

 '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 define your routes(app/https/routes.php).

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

That’s it.Do not forgot to create a directory public/uploads with 0777 permissions where script storing files.

Useful functions:

The getClientOriginalName() method used to get the actual name of the file when it was uploaded.

The getFilename() method used to get temporary file name given to our file on temporary location.

The getRealPath() method used to get current location of uploaded file.

The getClientSize() method used to get the size of the uploaded file in bytes.

The getClientMimeType() method used to get the mime type of uploaded file.

The guessClientExtension() method used to get extension of uploaded file.

The move() method used used to move uploaded file to target location.First parameter is the target or destination directory second parameter is name of the file.

0 0 votes
Article Rating
Subscribe
Notify of
guest

4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments