How to Upload a File in Laravel

File uploading is most used functionality in web applications.

Lots of application allows the users to manipulate files to the server like – profile image, upload documents, import data, etc.

In this tutorial, I show how you can validate and upload a file in Laravel.

How to Upload a File in Laravel


Contents

  1. Controller
  2. Route
  3. View
  4. Output
  5. Conclusion

1. Controller

Create a new PagesController controller.

php artisan make:controller PagesController

Here, create two methods –

  • index – Load index view.
  • uploadFile – This method calls on <form> submit. Read the submitted file with $request->file('file') and assign in $file.

Syntax –

$request->file([ file-element-name ]);

Get file details ( filename,extension, temporary location,file size, and mimeType ) using methods.

Define an $valid_extension Array variable to store valid extensions.

Assing max file size 2MB in Bytes to $maxFileSize.

Check file extension if it is valid then check its file size.

If it also valid then specify upload location in $location = 'images'.

Execute $file->move($location,$filename); to store the file.

The images folder is created inside the public/ directory at the root from where you can access the uploaded files.

NOTE – Folder automatically created if it does not exist.

Completed Code

<?php

namespace App\Http\Controllers;

use Session;
use Illuminate\Http\Request;

class PagesController extends Controller{

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

   public function uploadFile(Request $request){

     if ($request->input('submit') != null ){

        $file = $request->file('file');

        // File Details
        $filename = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $tempPath = $file->getRealPath();
        $fileSize = $file->getSize();
        $mimeType = $file->getMimeType();

        // Valid File Extensions
        $valid_extension = array("jpg","jpeg","png");

        // 2MB in Bytes
        $maxFileSize = 2097152;

        // Check file extension
        if(in_array(strtolower($extension),$valid_extension)){

          // Check file size
          if($fileSize <= $maxFileSize){

             // File upload location
             $location = 'images';

             // Upload file
             $file->move($location,$filename);

             Session::flash('message','Upload Successful.');
          }else{
             Session::flash('message','File too large. File must be less than 2MB.');
          }

        }else{
           Session::flash('message','Invalid File Extension.');
        }

      }

      // Redirect to index
      return redirect()->action('PagesController@index');
   }
}

2. Route

Open routes/web.php file.

Here, define two routes –

  • uploadFile – Post type route which calls on <form> submit.

Completed Code

<?php

Route::get('/', 'PagesController@index'); // localhost:8000/
Route::post('/uploadFile', 'PagesController@uploadFile');

3. View

Create a new index.blade.php file in resources/views/ directory.

Display Session message variable value in <p> if it is set.

Create a file element and a submit button in <form >. Also, add {{ csrf_field() }} inside <form>.

Set <form > action='/uploadFile' and enctype='multipart/form-data'.

Completed Code

<!doctype html>
<html>
  <head>
    <title>How to Upload a File in Laravel</title>
  </head>
  <body>
    <!-- Message -->
    @if(Session::has('message'))
      <p >{{ Session::get('message') }}</p>
    @endif

    <!-- Form -->
    <form method='post' action='/uploadFile' enctype='multipart/form-data' >
      {{ csrf_field() }}
      <input type='file' name='file' >
      <input type='submit' name='submit' value='Upload File'>
    </form>
  </body>
</html>

4. Output


5. Conclusion

In the example, I only used SESSION for displaying messages in the view file.

Modify the validation according to your requirement and you can find your files storage directory in public directory.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 1
  •  
  •  
  •  
  • 1
  •  

One Comment

  1. Justina Ng said:

    Good Post on Laravel. Am just learning this Laravel for a liitle project that I want to create. Eg. School Attendance System.

    Nice move Sir…..

    September 22, 2018
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *