Skip to main content

How to create remove and add more inputs functionality with input type file and text in Laravel?

Create remove and add more inputs functionality with input type file and text in Laravel

Blade file code   

  <form action="{{ route('storeDocuments') }}" method="post" enctype="multipart/form-data">

        @csrf

        <div id="inputFields">

            @if(!empty($documents[0]))

            @php $counter = 1000; @endphp

                @foreach($documents as $document)

                    <input type="hidden" id="document_id" name="documents[{{$counter}}][document_id]" value="{{$document->id}}">

                    <div class="field">

                        <label for="title">Title:</label>

                        <input type="text" id="title" class="title_input" name="documents[{{$counter}}][title]" value="{{$document->title}}" required>

                        <label for="description">Description:</label>

                        <textarea id="description" class="description_input" name="documents[{{$counter}}][description]">{{$document->description}}</textarea>

                        <label for="file">File:</label>

                        @if(!empty($document->file_path))

                        <a href="{{$document->file_path}}" class="doc_file">Download</a>

                        @endif

                        <input type="file" id="file" class="file_input" name="documents[{{$counter}}][file]" required>

                        <button class="remove">Remove</button>

                    </div>

                    @php $counter++ @endphp

                @endforeach

            @endif

            <div class="field">

                <label for="title">Title:</label>

                <input type="text" id="title" class="title_input" name="documents[0][title]" required>

                <label for="description">Description:</label>

                <textarea id="description" class="description_input" name="documents[0][description]"></textarea>

                <label for="file">File:</label>

                <input type="file" id="file" class="file_input" name="documents[0][file]" required>

                <button class="remove">Remove</button>

            </div>

        </div>

        <button id="addButton">Add More</button>

        <div class="col-sm-12">

            <div class="form-group mt-3">

                <div class="form-group submit">

                    <div class="form-submit">

                        <input type="submit" value="Submit" class="btn btn-success btn-lg" />

                    </div>

                </div>

            </div>

        </div>

    </form>

  <script>

    $(document).ready(function() {

       function removeButton(){

            var removeButtons = $(".remove");

            if (removeButtons.length == 1) {

                removeButtons.hide();

            }

            else{

                removeButtons.show();

            }

            console.log(removeButtons.length);

        }


        removeButton();

        $(".field").find('.remove').click(function() {

          $(this).parent().remove();

          removeButton();

        });

        let documentIndex = 1; // Initialize the document index

        $('#addButton').click(function(e) {

            documentIndex++;

            e.preventDefault();

            var newField = $('.field:last').clone();

            newField.find('.title_input').attr('name', 'documents[' + documentIndex + '][title]');

            newField.find('.description_input').attr('name', 'documents[' + documentIndex + '][description]');

            newField.find('.file_input').attr('name', 'documents[' + documentIndex + '][file]');

            newField.find('input').val('');

            newField.find('textarea').val('');

            $('#inputFields').append(newField);

            removeButton();

            // Add event listener for remove button

            newField.find('.remove').click(function() {

            $(this).parent().remove();

            removeButton();

            });

        });

    });

  </script>


Controller file

    public function store(Request $request,BaseHttpResponse $response)

    {

        $customer = auth('customer')->user();

        if(!empty($request->documents)){

            $documents = $request->documents;

            $insert_data = [];

            foreach($documents as $document){

                if(empty($document["title"]) && empty($document["description"]) && empty($document["file"])){

                    continue;

                }


                if(!empty($document["file"])){

                    // Accessing uploaded file from the request

                    $uploadedFile = $document["file"];


                    // Check if a file was uploaded

                    if ($uploadedFile && $uploadedFile->isValid()) {

                        // Get the original file name

                        $originalFileName = $uploadedFile->getClientOriginalName();


                        // Generate a unique filename

                        $uniqueFileName = pathinfo($originalFileName, PATHINFO_FILENAME) . '_' . time() . '.' . $uploadedFile->getClientOriginalExtension();


                        // Store the file in the storage disk with a unique filename

                        $storagePath = "documents" . "/" . $uniqueFileName;

                        $filePath = Storage::disk('uploads')->putFileAs('documents', $uploadedFile, $uniqueFileName);

                        $insert_data["file_path"] = $storagePath;                    

                    }

                }


                if(!empty($document["title"])){

                    $insert_data["title"] = $document["title"];

                }

                if(!empty($document["description"])){

                    $insert_data["description"] = $document["description"];

                }

                if(!empty($document["document_id"])){

                    $document_id = $document["document_id"];

                    $document = Document::find($document_id)->update($insert_data);

                }

                else{

                    $document = Document::create($insert_data);

                }


            }

        }

        $message = '';

        if(!empty($document->id)){

            $message = 'Documents data has been uploaded successfully';

        }

        return $response

        ->setNextUrl(url()->previous())

        ->setMessage(__($message));

    }

Comments

Popular posts from this blog

How to use inner html value or data in php from javascript(innerHTML)?

 use inner html value or data in php from javascript(innerHTML)? <html> <body> <p id="demo">use inner html value in php(innerhtml)</p> <script>   var jassi = document.getElementById("demo").innerHTML;   //document.write(jassi); </script> <?php $jassi = '<script>document.write(jassi);</script>'; echo $jassi; ?> </body> </html>

How to get store data from WCFM(Best Multi Vendor Marketplace) Plugin?

 Get store data from WCFM(Best Multi Vendor Marketplace) Plugin. global $WCFM, $WCFMmp, $wp, $WCFM_Query, $post; $store_id = ''; if ( isset( $attr['id'] ) && !empty( $attr['id'] ) ) { $store_id = absint($attr['id']); } if (  wcfm_is_store_page() ) { $wcfm_store_url = get_option( 'wcfm_store_url', 'store' ); $store_name = apply_filters( 'wcfmmp_store_query_var', get_query_var( $wcfm_store_url ) ); $store_id  = 0; if ( !empty( $store_name ) ) { $store_user = get_user_by( 'slug', $store_name ); } $store_id    = $store_user->ID; } $user_id = $store_id;  $vendor_data = get_user_meta( $user_id, 'wcfmmp_profile_settings', true ); $street_1 = $vendor_data['address']['street_1']; $street_2 = $vendor_data['address']['street_2']; $city     = $vendor_data['address']['city']; $zip      = $vendor_data['address']['zip&#

How to create login with phone number in woocommerce wordpress?

Create login with phone number in woocommerce wordpress. function wooc_extra_register_fields() {?>        <p class="form-row form-row-wide">        <label for="reg_billing_phone"><?php _e( 'Phone', 'woocommerce' ); ?><span class="required">*</span></label>        <input type="text" class="input-text" name="billing_phone" id="reg_billing_phone" value="<?php esc_attr_e( $_POST['billing_phone'] ); ?>" />        </p>            <?php  }  add_action( 'woocommerce_register_form_start', 'wooc_extra_register_fields' );  function wooc_validate_extra_register_fields( $username, $email, $validation_errors ) { if ( isset( $_POST['billing_phone'] ) ) {    $hasPhoneNumber= get_users('meta_value='.$_POST['billing_phone']);    if ( !empty($hasPhoneNumber)) {      $validation_er