Upload Multiple Images to Database With Different Ids Laravel
We volition build a uncomplicated multiple epitome upload system in Laravel. We will utilise a jQuery plugin to populate the paradigm field and submit multiple images to the server. The server checks all the inputs against divers validation, and if any of the validation fails, it will redirect to our create page with mistake messages.
Now let'south review each pace in more than item.
Laravel multiple images upload
To upload multiple images in Laravel, use the request facade. You can image upload with validation like images, mimes, max file upload, etc. It tin protect the upload script.
Steps to upload multiple images in Laravel
- Install and configure Laravel with the MySQL database.
- Create a migration, model, and controller file.
- Define the routes inside the routes >> spider web.php file.
- Add Laravel Prototype Validation inside the controller file and write the logic inside the controller that handles the multiple images coming from the server.
- The last stride is to create a grade, select multiple images, and upload them on the Laravel server.
Commencement, we download a fresh copy of the Laravel project by typing the post-obit command.
Footstep one: Configure Laravel.
composer create-project laravel/laravel multipleimages --adopt-dist
After installing the Laravel, configure the database. So get to the.envfile and add the database credentials.
Then we need to create a migration file to store the image'southward proper noun. So go to the CMD and hit the following control.
php artisan make:migration create_forms_table
Define the schema as follows.
<?php // create_forms_table.php use Illuminate\Back up\Facades\Schema; use Illuminate\Database\Schema\Blueprint; apply Illuminate\Database\Migrations\Migration; class CreateFormsTable extends Migration { /** * Run the migrations. * * @render void */ public part upward() { Schema::create('forms', function (Blueprint $tabular array) { $tabular array->increments('id'); $table->string('filename'); $table->timestamps(); }); } /** * Opposite the migrations. * * @return void */ public function down() { Schema::dropIfExists('forms'); } } The adjacent step will be to migrate this schema and brand a table in the database.
php artisan drift
We demand to fix upward the controller and model file for our awarding. Type the following command to generate a model and controller.
php artisan make:model Grade php artisan make:controller FormController
It volition generate two files.
- Course.php
- FormController.php
Stride 2: Ascertain routes in the web.php file.
Go to the routes >> spider web.php file and add the following routes.
// spider web.php Route::get('class','FormController@create'); Route::post('form','FormController@store'); In the FormController'due south, create a part write the following code.
// FormController.php /** * Show the form for creating a new resource. * * @render \Illuminate\Http\Response */ public function create() { // return view('create'); } At present, let u.s. make acreate.blade.phpfile inside the viewsfolder.
<html lang="en"> <head> <title>Laravel Multiple File Upload Example</championship> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.nine.ane/jquery.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.three.6/css/bootstrap.min.css"> </head> <body> <div form="container"> <h3 class="jumbotron">Laravel Multiple File Upload</h3> <form method="post" activeness="{{url('form')}}" enctype="multipart/form-data"> {{csrf_field()}} <div class="input-grouping control-group increment" > <input type="file" name="filename[]" form="form-command"> <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" course="btn btn-primary" style="margin-top:10px">Submit</button> </course> </div> </body> </html> Here, I have taken a straightforward course to add the images. Withal, we demand functionality to populate the input field when we click the add button. So beginning, let us do that. We have used jQuery for that feature.
Step 3: Add the jQuery code to populate the input field.
Our file looks like this after calculation the jQuery code and some HTML lawmaking to insert dynamic input fields.
<html lang="en"> <head> <title>Laravel Multiple File Upload Instance</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/iii.3.6/css/bootstrap.min.css"> </head> <body> <div class="container"> <h3 form="jumbotron">Laravel Multiple File Upload</h3> <form method="mail service" action="{{url('form')}}" enctype="multipart/grade-data"> {{csrf_field()}} <div course="input-grouping control-group increase" > <input type="file" proper noun="filename[]" class="class-control"> <div class="input-group-btn"> <button class="btn btn-success" blazon="button"><i course="glyphicon glyphicon-plus"></i>Add</button> </div> </div> <div course="clone hibernate"> <div class="command-group input-group" mode="margin-summit:10px"> <input type="file" proper name="filename[]" class="class-control"> <div class="input-group-btn"> <button class="btn btn-danger" type="button"><i grade="glyphicon glyphicon-remove"></i> Remove</button> </div> </div> </div> <button type="submit" class="btn btn-primary" way="margin-top:10px">Submit</button> </form> </div> <script type="text/javascript"> $(certificate).ready(function() { $(".btn-success").click(function(){ var html = $(".clone").html(); $(".increment").after(html); }); $("body").on("click",".btn-danger",part(){ $(this).parents(".control-group").remove(); }); }); </script> </torso> </html> Step 5: Add Laravel Prototype validation.
We are inserting multiple images, and then; we need to make an array validation in our project. In aFormController.phpfile, add the following code to validate our input file.
// FormController.php $this->validate($request, [ 'filename' => 'required', 'filename.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048' ]);
It checks confronting the required field also every bit the image type. If the input file does not contain paradigm or jpg, png, gif, or svg, it throws an error, and laravel catches it and displays these errors in the frontend. To testify errors in the form, nosotros demand to write the following code later on the container class.
// create.blade.php @if (count($errors) > 0) <div course="warning alarm-danger"> <strong>Whoops!</strong> There were some issues with your input.<br><br> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif Okay, and then hither validation is washed.
Step half-dozen: Insert multiple images in the database.
After checking the validation, we need to shop the image names in our database. And so our final code to insert the various images on the database is the post-obit.
// FormController.php /** * Store a newly created resources in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public office store(Asking $request) { $this->validate($request, [ 'filename' => 'required', 'filename.*' => 'prototype|mimes:jpeg,png,jpg,gif,svg|max:2048' ]); if($asking->hasfile('filename')) { foreach($request->file('filename') as $image) { $name=$image->getClientOriginalName(); $image->move(public_path().'/images/', $name); $data[] = $proper noun; } } $grade= new Form(); $grade->filename=json_encode($data); $course->save(); return back()->with('success', 'Your images has been successfully'); } If the input file is the image, it volition loop through all the images ane past ane, store the image names in the assortment, and then insert that array in the database.
I am using json_encode to insert the multiple-image names in one row.
You lot can make another table and so add the strange key to that table. Later success, nosotros need to display a success bulletin. So write that code in thecreate.blade.php file.
// create.blade.php @if(session('success')) <div class="warning alert-success"> {{ session('success') }} </div> @endif So, our concludingcreate.blade.phpfile looks like this.
// create.bract.php <html lang="en"> <caput> <title>Laravel Multiple File Upload Example</championship> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.nine.i/jquery.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> </head> <torso> <div grade="container"> @if (count($errors) > 0) <div form="alarm alert-danger"> <stiff>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 alarm-success"> {{ session('success') }} </div> @endif <h3 class="jumbotron">Laravel Multiple File Upload</h3> <form method="mail" action="{{url('form')}}" enctype="multipart/form-information"> {{csrf_field()}} <div class="input-group control-grouping increment" > <input type="file" name="filename[]" class="form-control"> <div form="input-group-btn"> <button class="btn btn-success" type="button"><i class="glyphicon glyphicon-plus"></i>Add together</push> </div> </div> <div course="clone hide"> <div class="control-group input-group" fashion="margin-meridian:10px"> <input blazon="file" name="filename[]" grade="form-command"> <div class="input-group-btn"> <button form="btn btn-danger" type="push"><i class="glyphicon glyphicon-remove"></i> Remove</push button> </div> </div> </div> <button type="submit" grade="btn btn-principal" manner="margin-elevation:10px">Submit</button> </grade> </div> <script type="text/javascript"> $(document).ready(function() { $(".btn-success").click(function(){ var html = $(".clone").html(); $(".increment").subsequently(html); }); $("body").on("click",".btn-danger",office(){ $(this).parents(".command-group").remove(); }); }); </script> </trunk> </html> I have already put this lawmaking on Github.
Github Repository
Recommended Posts
Laravel Paradigm Intervention
Laravel Avatar Image Upload
Laravel Dropzone Image Upload
Laravel File Upload
Laravel Deject File Upload
Source: https://appdividend.com/2022/02/28/laravel-multiple-images-upload/
Post a Comment for "Upload Multiple Images to Database With Different Ids Laravel"