How to Cancel Upload Request to Database

We will build a uncomplicated multiple epitome upload system in Laravel. We will use a jQuery plugin to populate the image field and submit multiple images to the server. The server checks all the inputs against divers validation, and if whatever of the validation fails, it volition redirect to our create folio with error messages.

Now let'due south review each step in more detail.

Laravel multiple images upload

To upload multiple images in Laravel, utilise the request facade. You tin can prototype upload with validation like images, mimes, max file upload, etc. It can protect the upload script.

Steps to upload multiple images in Laravel

  1. Install and configure Laravel with the MySQL database.
  2. Create a migration, model, and controller file.
  3. Ascertain the routes inside the routes >> web.php file.
  4. Add Laravel Image Validation inside the controller file and write the logic inside the controller that handles the multiple images coming from the server.
  5. The final step is to create a course, select multiple images, and upload them on the Laravel server.

Commencement, we download a fresh copy of the Laravel project past typing the following command.

Stride 1: Configure Laravel.

composer create-project laravel/laravel multipleimages --adopt-dist

Afterwards installing the Laravel, configure the database. And then become to the.envfile and add the database credentials.

And then nosotros demand to create a migration file to shop the prototype'south name. Then go to the CMD and hit the post-obit command.

php artisan make:migration create_forms_table

Define the schema every bit follows.

<?php  // create_forms_table.php  use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Design; apply Illuminate\Database\Migrations\Migration;  class CreateFormsTable extends Migration {     /**      * Run the migrations.      *      * @render void      */     public office up()     {         Schema::create('forms', function (Blueprint $table) {             $table->increments('id');             $tabular array->string('filename');             $table->timestamps();         });     }      /**      * Reverse the migrations.      *      * @return void      */     public function down()     {         Schema::dropIfExists('forms');     } }

The next step will be to migrate this schema and make a table in the database.

php artisan migrate

We need to gear up the controller and model file for our application. Blazon the post-obit command to generate a model and controller.

php artisan brand:model Class  php artisan make:controller FormController

It volition generate ii files.

  1. Form.php
  2. FormController.php

Step ii: Define routes in the web.php file.

Become to the routes  >>  spider web.php file and add the following routes.

// web.php  Route::get('form','FormController@create'); Route::post('form','FormController@store');

In the FormController's, create a function write the following code.

// FormController.php  /**      * Show the form for creating a new resources.      *      * @render \Illuminate\Http\Response      */     public role create()     {         //         return view('create');     }        

Now, allow us make acreate.blade.phpfile inside the viewsfolder.

<html lang="en"> <head>   <title>Laravel Multiple File Upload Case</championship>   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.nine.1/jquery.js"></script>   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> </head> <trunk>      <div course="container">             <h3 class="jumbotron">Laravel Multiple File Upload</h3> <form method="post" action="{{url('grade')}}" enctype="multipart/class-data">   {{csrf_field()}}          <div class="input-group command-group increment" >           <input blazon="file" name="filename[]" grade="form-control">           <div class="input-group-btn">              <button class="btn btn-success" type="button"><i grade="glyphicon glyphicon-plus"></i>Add</button>           </div>         </div>          <button blazon="submit" class="btn btn-primary" style="margin-top:10px">Submit</button>    </form>           </div>  </body> </html>

Here, I have taken a straightforward class to add the images. However, we demand functionality to populate the input field when we click the add button. So showtime, let us practise that. We have used jQuery for that characteristic.

Step 3: Add together the jQuery lawmaking 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 Example</title>   <script src="http://ajax.googleapis.com/ajax/libs/jquery/one.ix.1/jquery.js"></script>   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.three.6/css/bootstrap.min.css"> </head> <trunk>        <div class="container">      <h3 class="jumbotron">Laravel Multiple File Upload</h3> <form method="postal service" action="{{url('form')}}" enctype="multipart/form-data">   {{csrf_field()}}          <div class="input-group control-grouping increase" >           <input type="file" proper name="filename[]" class="course-command">           <div class="input-grouping-btn">              <button class="btn btn-success" type="push button"><i class="glyphicon glyphicon-plus"></i>Add together</button>           </div>         </div>         <div class="clone hide">           <div class="control-grouping input-group" style="margin-top:10px">             <input type="file" proper noun="filename[]" grade="form-control">             <div class="input-group-btn">                <push class="btn btn-danger" blazon="button"><i class="glyphicon glyphicon-remove"></i> Remove</push>             </div>           </div>         </div>          <push type="submit" form="btn btn-principal" mode="margin-top:10px">Submit</push>    </class>           </div>   <script blazon="text/javascript">      $(document).ready(function() {        $(".btn-success").click(function(){            var html = $(".clone").html();           $(".increment").after(html);       });        $("trunk").on("click",".btn-danger",function(){            $(this).parents(".control-group").remove();       });      });  </script>   </body> </html>        

Pace five: Add Laravel Image validation.

Nosotros are inserting multiple images, and then; we need to brand an assortment validation in our project. In aFormController.phpfile, add the following lawmaking to validate our input file.

// FormController.php  $this->validate($request, [     'filename' => 'required',     'filename.*' => 'prototype|mimes:jpeg,png,jpg,gif,svg|max:2048' ]);        

Information technology checks against the required field as well every bit the image type. If the input file does non contain image or jpg, png, gif, or svg, it throws an error, and laravel catches it and displays these errors in the frontend. To show errors in the form, we need to write the post-obit code later on the container class.

// create.blade.php        @if (count($errors) > 0)       <div class="alert alarm-danger">         <strong>Whoops!</stiff> There were some problems with your input.<br><br>         <ul>           @foreach ($errors->all() every bit $error)               <li>{{ $error }}</li>           @endforeach         </ul>       </div>       @endif

Okay, and so here validation is washed.

jQuery Dynamic Fields

Step 6: Insert multiple images in the database.

Later on checking the validation, we need to shop the image names in our database. So our last code to insert the various images on the database is the following.

// FormController.php  /**      * Shop a newly created resource in storage.      *      * @param  \Illuminate\Http\Request  $asking      * @return \Illuminate\Http\Response      */     public function store(Request $request)      {          $this->validate($request, [                  'filename' => 'required',                 'filename.*' => 'prototype|mimes:jpeg,png,jpg,gif,svg|max:2048'          ]);                  if($request->hasfile('filename'))          {              foreach($asking->file('filename') as $image)             {                 $name=$image->getClientOriginalName();                 $prototype->motility(public_path().'/images/', $name);                   $data[] = $proper noun;               }          }           $form= new Form();          $course->filename=json_encode($information);                            $course->save();          return dorsum()->with('success', 'Your images has been successfully');     }

If the input file is the epitome, information technology will loop through all the images one by one, store the image names in the array, and so insert that array in the database.

I am using json_encode to insert the multiple-paradigm names in one row.

Yous can make another table and then add the foreign key to that tabular array. Later on success, nosotros demand to brandish a success message. And so write that lawmaking in thecreate.blade.php file.

// create.bract.php   @if(session('success'))    <div class="alarm alert-success">       {{ session('success') }}    </div>   @endif

And then, our finalcreate.blade.phpfile 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/one.9.ane/jquery.js"></script>   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/three.iii.vi/css/bootstrap.min.css"> </head> <trunk>   <div class="container">       @if (count($errors) > 0)       <div course="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('class')}}" enctype="multipart/class-data">   {{csrf_field()}}          <div class="input-group control-grouping increment" >           <input type="file" name="filename[]" course="form-control">           <div grade="input-grouping-btn">              <push button class="btn btn-success" blazon="push"><i course="glyphicon glyphicon-plus"></i>Add</button>           </div>         </div>         <div class="clone hide">           <div course="control-grouping input-group" style="margin-top:10px">             <input type="file" name="filename[]" course="form-control">             <div class="input-group-btn">                <button grade="btn btn-danger" type="push"><i class="glyphicon glyphicon-remove"></i> Remove</button>             </div>           </div>         </div>          <button type="submit" form="btn btn-primary" fashion="margin-elevation:10px">Submit</button>    </course>           </div>   <script type="text/javascript">       $(document).ready(role() {        $(".btn-success").click(function(){            var html = $(".clone").html();           $(".increment").subsequently(html);       });        $("body").on("click",".btn-danger",office(){            $(this).parents(".control-group").remove();       });      });  </script> </trunk> </html>

I take already put this code on Github.

Github Repository

Recommended Posts

Laravel Image Intervention

Laravel Avatar Epitome Upload

Laravel Dropzone Image Upload

Laravel File Upload

Laravel Cloud File Upload

vanwagonerthosell.blogspot.com

Source: https://appdividend.com/2022/02/28/laravel-multiple-images-upload/

0 Response to "How to Cancel Upload Request to Database"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel