Laravel Multiple File Upload

Getting Started

First, we're going to create a new project and I'm gonna name it upload and add it to localhost with the name upload.dev. If you have no idea on how to do this, please refer to my tutorial Installing Laravel - PHP Framework.

Setting up our Database

1. Open your phpMyAdmin and create a new database. In my case, I've created a database named upload. 2. In our project, open .env file and update the ff lines depending on your setting.
  1. DB_DATABASE=upload
  2. DB_USERNAME=root
  3. DB_PASSWORD=

Creating our Controller

1. In command prompt, navigate to your project and type: php artisan make:controller UploadController This will create our controller in the form of UploadController.php located in app/Http/Controllers folder. 2. Open UploadController.php and edit it with the ff codes:
  1. <?php
  2.  
  3. namespace App\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6. use App\File;
  7.  
  8. class UploadController extends Controller
  9. {
  10. public function index(){
  11.  
  12. $files = File::all();
  13.  
  14. return view('upload')->with('files', $files);
  15. }
  16.  
  17. public function store(Request $request){
  18.  
  19. $messages = [
  20. 'required' => 'Please select file to upload',
  21. ];
  22.  
  23. $this->validate($request, [
  24. 'file' => 'required',
  25. ], $messages);
  26.  
  27. foreach ($request->file as $file) {
  28. $filename = time().'_'.$file->getClientOriginalName();
  29. $filesize = $file->getClientSize();
  30. $file->storeAs('public/',$filename);
  31. $fileModel = new File;
  32. $fileModel->name = $filename;
  33. $fileModel->size = $filesize;
  34. $fileModel->location = 'storage/'.$filename;
  35. $fileModel->save();
  36. }
  37.  
  38. return redirect('/')->with('success', 'File/s Uploaded Successfully');
  39.  
  40. }
  41.  
  42. }

Creating our Model

1. In command prompt, navigate to our project and type: php artisan make:model File -m This will create our model File.php located in app folder. It will also create the migration for us due to the -m that we added in creating the model in the form of, in my case 2017_11_18_065104_create_files_table.php file located in database/migrations folder. 1. Open 2017_11_18_065104_create_files_table.php and edit it with ff codes:
  1. <?php
  2.  
  3. use Illuminate\Support\Facades\Schema;
  4. use Illuminate\Database\Schema\Blueprint;
  5. use Illuminate\Database\Migrations\Migration;
  6.  
  7. class CreateFilesTable extends Migration
  8. {
  9. /**
  10.   * Run the migrations.
  11.   *
  12.   * @return void
  13.   */
  14. public function up()
  15. {
  16. Schema::create('files', function (Blueprint $table) {
  17. $table->increments('id');
  18. $table->string('name');
  19. $table->string('size');
  20. $table->string('location');
  21. $table->timestamps();
  22. });
  23. }
  24.  
  25. /**
  26.   * Reverse the migrations.
  27.   *
  28.   * @return void
  29.   */
  30. public function down()
  31. {
  32. Schema::dropIfExists('files');
  33. }
  34. }

Migrating

In command prompt, navigate to your project and type: php artisan migrate It will then create our database migration. [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was t oo long; max key length is 767 bytes (SQL: alter table `users` add unique ` users_email_unique`(`email`)) You can solve this by opening AppServiceProvider.php located in app/Providers folder. Add this line: use Illuminate\Support\Facades\Schema; In boot add this line: Schema::defaultStringLength(191); migration error laravel Run php artisan migrate again and make sure that your database is empty because it will have another error if its not.

Creating our Routes

In routes folder, open web.php and edit it with the ff codes:
  1. <?php
  2. Route::get('/','UploadController@index');
  3.  
  4. Route::post('/store','UploadController@store')->name('upload.file');

Creating our Views

In resources/views folder, create the ff files: upload.blade.php
  1. <!DOCTYPE html>
  2. <meta charset="UTF-8">
  3. <title>Laravel File Upload</title>
  4. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
  5. <link rel="stylesheet" href="/css/app.css">
  6. </head>
  7. <div class="container">
  8. <h1 class="page-header text-center">Laravel File Upload</h1>
  9. <div class="row">
  10. <div class="col-md-4">
  11. <div class="well">
  12. <h2 class="text-center">Upload Form</h2>
  13. <form method="POST" action="{{ route('upload.file') }}" enctype="multipart/form-data">
  14. {{ csrf_field() }}
  15. <input type="file" name="file[]" multiple><br>
  16. <button type="submit" class="btn btn-primary">Upload</button>
  17. </form>
  18. </div>
  19. <div style="margin-top:20px;">
  20. @if(count($errors) > 0)
  21. @foreach($errors->all() as $error)
  22. <div class="alert alert-danger text-center">
  23. {{$error}}
  24. </div>
  25. @endforeach
  26. @endif
  27.  
  28. @if(session('success'))
  29. <div class="alert alert-success text-center">
  30. {{session('success')}}
  31. </div>
  32. @endif
  33. </div>
  34. </div>
  35. <div class="col-md-8">
  36. <h2>Files Table</h2>
  37.  
  38. <table class="table table-bordered table-striped">
  39. <th>File Name</th>
  40. <th>File Size</th>
  41. <th>Date Uploaded</th>
  42. <th>File Location</th>
  43. </thead>
  44. @if(count($files) > 0)
  45. @foreach($files as $file)
  46. <tr>
  47. <td>{{ $file->name }}</td>
  48. <td>
  49. @if($file->size < 1000)
  50. {{ number_format($file->size,2) }} bytes
  51. @elseif($file->size >= 1000000)
  52. {{ number_format($file->size/1000000,2) }} mb
  53. @else
  54. {{ number_format($file->size/1000,2) }} kb
  55. @endif
  56. </td>
  57. <td>{{ date('M d, Y h:i A', strtotime($file->created_at)) }}</td>
  58. <td><a href="{{ $file->location }}">{{ $file->location }}</a></td>
  59. </tr>
  60. <!--<img src='storage/upload/{{$file->name}}' name="{{$file->name}}" class="thumbnail">-->
  61. @endforeach
  62. @else
  63. <tr>
  64. <td colspan="4" class="text-center">No Table Data</td>
  65. </tr>
  66. @endif
  67. </tbody>
  68. </table>
  69.  
  70.  
  71.  
  72. </div>
  73. </div>
  74. </div>
  75. </body>
  76. </html>

Setting up Max Upload Size

We set up our upload size to prevent us from getting errors if the file we uploaded exceeded our upload size. In XAMPP, open php/php.ini. Search for the ff lines and update their value:
  1. post_max_size=120M
  2. upload_max_filesize=100M
Don't forget to restart XAMPP for this update to work.

Running our Server

In your web browser, type the name that you added in localhost for your project in my case, upload.dev. That ends this tutorial. Happy Coding :)

Add new comment