Haschwalth
Haschwalth

Reputation: 25

Insert data to multiple tables takes too long and eventually the route stops responding

I created a customer module from a single form consisting of two tables, the customer table (company) and the person_in_charges table (adding several PIC data for one customer data with a maximum of 5 PIC data).

On the create customer page, there is a form to send data to: the customer table consists of: user_id, name, NPWP (Tax Identification Number), file_path (company logo), and address. the person_in_charges table consists of: customer_id, pic_name, pic_email, and pic_phone.

The website works fine when I haven't added customer data with PIC yet. However, when I add customer data and click the 'create customer' button, the page only responds with loading, then displays an error message 'maximum execution time of 60 seconds exceeded'. However, customer and PIC data have been successfully added when I checked the database. After a while of the error appearing, the website for the 'customer' URL cannot be accessed.

I tried deleting data from the person_in_charges table and only keeping data from the customer table, or I tried deleting customer data and only keeping data from the person_in_charges table, then the 'customer' URL functions normally again. blade

<form method="POST" action="{{ route('customers.store') }}" enctype="multipart/form-data">
 @csrf
 <div class="row">
  <div class="col-lg-3 mb-2">
   <label for="name" class="form-label">Name</label>
   <input value="{{ old('name') }}" type="text" class="form-control @error('name') is-invalid @enderror" name="name" placeholder="Company Name" autofocus required>
   @error('name')
    <span class="invalid-feedback text-left" role="alert">
     <strong>{{ $message }}</strong>
    </span>
   @enderror
  </div>
  <div class="col-lg-3 mb-2">
   <label for="npwp" class="form-label">NPWP</label>
   <input value="{{ old('npwp') }}" type="text" class="form-control @error('npwp') is-invalid @enderror" name="npwp" placeholder="Without (-)" required>
   @error('npwp')
    <span class="invalid-feedback text-left" role="alert">
     <strong>{{ $message }}</strong>
    </span>
   @enderror
  </div>
  <div class="col-lg-3 mb-2">
   <label for="image" class="form-label mb-2">Picture</label>
   <input id="image" name="file_path" type="file" class="form-control @error('file_path') is-invalid @enderror" onchange="previewImage()" accept="image/*" required>
   @error('file_path')
    <span class="invalid-feedback text-left" role="alert">
     <strong>{{ $message }}</strong>
    </span>
   @enderror
  </div>
  <div class="col-lg-3 mb-2">
   <img class="img-preview img-fluid col-lg-5" style="display:none;">
  </div>
 </div>
 <div class="row">
  <div class="col-lg-3 mb-4">
   <label for="address" class="form-label">Address</label>
   <textarea id="address" name="address" class="form-control" data-height="100">{{ old('address') }}</textarea>
   @error('address')
    <span class="text-danger text-left">{{ $message }}</span>
   @enderror
  </div>
  <div class="col-lg-9">
   <div id="pic-container">
    <div class="pic">
     <label for="pic_name[]" class="form-label">Person In Charge</label>
      <div class="row mb-2">
       <div class="col-lg-3">
        <input value="{{ old('pic_name.0') }}" type="text" class="form-control @error('pic_name.0') is-invalid @enderror" name="pic_name[]" placeholder="PIC Name" required>
        @error('pic_name.0')
         <span class="text-danger text-left">{{ $message }}</span>
        @enderror
       </div>
       <div class="col-lg-3">
        <input value="{{ old('pic_email.0') }}" type="email" class="form-control @error('pic_email.0') is-invalid @enderror" name="pic_email[]" placeholder="PIC Email" required>
        @error('pic_email.0')
         <span class="text-danger text-left">{{ $message }}</span>
        @enderror
       </div>
       <div class="col-lg-3">
        <input value="{{ old('pic_phone.0') }}" type="text" class="form-control @error('pic_phone.0') is-invalid @enderror" name="pic_phone[]" placeholder="62xxxxxxxxx" required>
        @error('pic_phone.0')
         <span class="text-danger text-left">{{ $message }}</span>
        @enderror
       </div>
       <div class="col-lg-3">
        <button type="button" class="btn btn-success mt-1 add-pic"><i class="fa-solid fa-plus"></i></button>
       </div>
      </div>
     </div>
    </div>
   </div>
  </div>
  <button type="submit" class="btn btn-primary">Create Customer</button>
</form>

<script>
        $(document).ready(function() {
            // Add new PIC fields
            $('.add-pic').click(function() {
                // Count the number of existing pic elements
                var count = $('.pic').length;

                // Add new pic element only if count is less than 5
                if (count < 5) {
                    var newPic = $('<div>').addClass('pic');
                    var rowDiv = $('<div>').addClass('row mb-4');
                    rowDiv.append($('<div>').addClass('col-lg-3').append($('<input>').attr({
                        type: 'text',
                        name: 'pic_name[]',
                        placeholder: 'PIC Name',
                        value: "{{ old('pic_name[]') }}",
                        class: 'form-control',
                        required: true
                    })).append($('<span>').addClass('text-danger text-left').text("{{ $errors->first('pic_name[]') }}")));
                    rowDiv.append($('<div>').addClass('col-lg-3').append($('<input>').attr({
                        type: 'email',
                        name: 'pic_email[]',
                        placeholder: 'PIC Email address',
                        value: "{{ old('pic_email[]') }}",
                        class: 'form-control',
                        required: true
                    })).append($('<span>').addClass('text-danger text-left').text("{{ $errors->first('pic_email[]') }}")));
                    rowDiv.append($('<div>').addClass('col-lg-3').append($('<input>').attr({
                        type: 'text',
                        name: 'pic_phone[]',
                        placeholder: '62xxxxxxxxx',
                        value: "{{ old('pic_phone[]') }}",
                        class: 'form-control',
                        required: true
                    })).append($('<span>').addClass('text-danger text-left').text("{{ $errors->first('pic_phone[]') }}")));
                    rowDiv.append($('<div>').addClass('col-lg-3').append($('<button>').attr({
                        type: 'button',
                        class: 'btn btn-danger mt-1 remove-pic',
                    }).append($('<i>').addClass('fa-solid fa-minus'))));
                    newPic.append(rowDiv);

                    $('#pic-container').append(newPic);
                } else {
                    alert('You can only add up to 5 Person In Charge.');
                }
            });

            // Remove PIC fields
            $(document).on('click', '.remove-pic', function() {
                $(this).closest('.pic').remove();
            });
        });
    </script>

controller

public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|max:100',
            'npwp' => 'required|digits_between:15,16|numeric',
            'address' => 'required',
            'file_path' => 'required|image|mimes:png,jpeg,jpg|max:1024',
            'pic_name.*' => 'required',
            'pic_email.*' => 'required|email:rfc,dns',
            'pic_phone.*' => 'required|numeric|digits_between:10,13'
        ]);
        $customerName = str_replace(' ', '_', strtolower($validated['name']));
        $filename = $customerName . '_' . str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT) . '.' . $request->file('file_path')->getClientOriginalExtension();

        DB::beginTransaction();
        try {
            $customer = new Customer;
            $customer->user_id = auth()->user()->id;
            $customer->name = $validated['name'];
            $customer->npwp = $validated['npwp'];
            $customer->address = $validated['address'];
            $customer->file_path = $request->file('file_path')->storeAs('customers-images', $filename, 'public');
            $customer->save();

            $pics = [];
            foreach ($validated['pic_name'] as $key => $value) {
                if ($key < 5) { // maksimal 5 pic
                    $pics[] = new PersonInCharge([
                        'customer_id' => $customer->id,
                        'pic_name' => $validated['pic_name'][$key],
                        'pic_email' => $validated['pic_email'][$key],
                        'pic_phone' => $validated['pic_phone'][$key]
                    ]);
                }
            }
            $customer->personInCharge()->saveMany($pics);
            DB::commit();

            return redirect()->route('customers.index')->with('success', "Customer added successfully!");
        } catch (Exception $e) {
            DB::rollback();
            return redirect()->back()->withInput()->with('error', 'Failed to add customer. ' . $e->getMessage());
        }
    }

error enter image description here

I have tried previously using ini_set('max_execution_time', 600); and set_time_limit(300); but the bug still appears.

Do you have any suggestions or solutions regarding my problem? Thank you for your response.

Upvotes: 0

Views: 50

Answers (0)

Related Questions