Laravel Multiple Files Upload Tutorial Example From Scratch is leading topic. We are going to build multiple files upload system using Laravel 5.5. In the frontend, We will use a jQuery plugin to populate file field and submit the more than one file to the server. It will always be excellent if you use laravel validation for your web form in laravel project.In this tutorial, I will show you how to use laravel default validation with jQuery ajax.The server validates all the inputs against defined validation, and if any of the validation is going to fail, then it will redirect to our create page with error messages.
Laravel Multiple Files Upload Tutorial
Content Overview [hide]
First, we download a new copy of Laravel project by typing the following command.
composer create-project laravel/laravel multiplefiles --prefer-dist
After establishing the Laravel, configure the database. So go to the .env file and continue the database credentials.
Next, we need to create a migration file to store the images name. So go to the CMD and kicked the following command.
php artisan make:migration create_files_table
Define the schema as follows.
<?php
// create_files_table.php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFormsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('files', function (Blueprint $table) {
$table->increments('id');
$table->string('filename');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('files');
}
}
Then migrate this schema and make a table in the database.
php artisan migrate
Step 2: Define model, controller, and routes.
Hit the following command to generate model and controller.
php artisan make:model File
php artisan make:controller FileController
It will generate two files.
- File.php
- FileController.php
Now define routes in routes >> web.php file and add the following routes.
// web.php
Route::get('file','FileController@create');
Route::post('file','FileController@store');
In the FileController’s create a function, write the following code.
// FileController.php
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return view('create');
}
Immediately, make a create.blade.php file inside views folder.
<html lang="en">
<head>
<title>Laravel Multiple File Upload Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="input-group control-group increment" >
<input type="file" name="filename[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
</div>
</div>
<button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>
</form>
</div>
</body>
</html>
Here, I have taken a natural form to add the files. We need a functionality when we can populate the input field when we click add button. So first let us do that. We have used jQuery for that feature.
Step 3: Add jQuery code to populate input field.
After adding the jQuery code and some HTML code to insert effective input fields, our file looks like this.
<html lang="en">
<head>
<title>Laravel Multiple File Upload Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="input-group control-group increment" >
<input type="file" name="filename[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
</div>
</div>
<div class="clone hide">
<div class="control-group input-group" style="margin-top:10px">
<input type="file" name="filename[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".btn-success").click(function(){
var html = $(".clone").html();
$(".increment").after(html);
});
$("body").on("click",".btn-danger",function(){
$(this).parents(".control-group").remove();
});
});
</script>
</body>
</html>
Step 4: Add the backend validation.
We are inserting multiple files so; we need to make array validation in our project. In a FileController.php file, add the following code to validate our input file.
// FileController.php
$this->validate($request, [
'filename' => 'required',
'filename.*' => 'mimes:doc,pdf,docx,zip'
]);
It validates against the required field as well file type. If the input file does not contain file or doc, pdf, docx, zip then it throws an error and laravel catch it and demonstrates these errors in the frontend. To show errors in the form, we need to write the following code after container class.
// create.blade.php
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
Okay, so here validation is done.
Step 5: Insert multiple files into the database.
After checking the validation, we need to store the file names in our database. So our final code to insert the various files in the database is following.
// FileController.php
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'filename' => 'required',
'filename.*' => 'mimes:doc,pdf,docx,zip'
]);
if($request->hasfile('filename'))
{
foreach($request->file('filename') as $file)
{
$name=$file->getClientOriginalName();
$file->move(public_path().'/files/', $name);
$data[] = $name;
}
}
$file= new File();
$file->filename=json_encode($data);
$file->save();
return back()->with('success', 'Your files has been successfully added');
}
If the input is a file, then it will loop through all the files one by one and store the file names in the array and then insert that array in the database. I am using json_encode to include the multiple file names in one row. You can make another table and then append the foreign key to that table. After success, we need to display a success message. So write that code in the create.blade.php file.
// create.blade.php
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
So, our final create.blade.php file looks like this.
// create.blade.php
<html lang="en">
<head>
<title>Laravel Multiple File Upload Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="container">
@if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@if(session('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<h3 class="jumbotron">Laravel Multiple File Upload</h3>
<form method="post" action="{{url('file')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="input-group control-group increment" >
<input type="file" name="filename[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add</button>
</div>
</div>
<div class="clone hide">
<div class="control-group input-group" style="margin-top:10px">
<input type="file" name="filename[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-danger" type="button"><i class="glyphicon glyphicon-remove"></i> Remove</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".btn-success").click(function(){
var html = $(".clone").html();
$(".increment").after(html);
});
$("body").on("click",".btn-danger",function(){
$(this).parents(".control-group").remove();
});
});
</script>
</body>
</html>
Now, you can able to upload multiple files. Of course, images and other file formats are not allowed. Finally, our Laravel Multiple Files Upload Tutorial Example From Scratch is over.
Link : https://appdividend.com/2018/02/09/laravel-multiple-files-upload-tutorial-example/
Link : https://appdividend.com/2018/02/09/laravel-multiple-files-upload-tutorial-example/
No comments:
Post a Comment