Search Function In Laravel With The Help OF JS

Posted by

Step 1:- Write A Code In Html

<div class="col-12 p-3">
          <input type="text" class="form-control" name="manual_filter_table" id="filter_by_search" placeholder="Search .." style="font-size:18px; border:1px solid blue;">
        </div>

Step 2:- Make A Route

Route::get('/myorder_search', [App\Http\Controllers\Admin\PaymentController::class, 'myordersearch'])->name('myorder_search');

Step 3:- Make A New Function In controller

 public function myordersearch(Request $request)
    {
        $id = Auth::user()->id;
        $search = $request->input('search');

        $query = paypal::query();

        if (!empty($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('org_slug', 'LIKE', '%' . $search . '%')
                    ->orWhere('payer_id', 'LIKE', '%' . $search . '%')
                    ->orWhere('payment_id', 'LIKE', '%' . $search . '%')
                    ->orWhere('payment_status', 'LIKE', '%' . $search . '%')
                    ->orWhere('influencer_name', 'LIKE', '%' . $search . '%')
                    ->orWhere(function ($q) use ($search) {
                        $q->whereRaw("DATE_FORMAT(created_at, '%Y-%m-%d') LIKE ?", ['%' . $search . '%'])
                            ->orWhereRaw("DATE_FORMAT(created_at, '%Y-%m') LIKE ?", ['%' . $search . '%'])
                            ->orWhereRaw("DATE_FORMAT(created_at, '%Y') LIKE ?", ['%' . $search . '%']);
                    })
                    ->orWhereRaw("CONCAT(amount, ' ', currency) LIKE ?", ['%' . $search . '%']);
            });
        }

        $users = $query->where('admin_id', $id)->get();

        $names = [];
        foreach ($users as $order) {
            $influencerNames = json_decode($order->influencer_name, true);
            foreach ($influencerNames as $name) {
                $names[] = $name['influencer_name'];
            }
        }

        $formattedNames = implode(' | ', array_unique($names));

        return response()->json([
            'users' => $users,
            'formattedNames' => $formattedNames
        ]);
    }

Step 4:- Write A Code In Javascript

<script>
  document.addEventListener('DOMContentLoaded', function() {
    var filterInput = document.getElementById('filter_by_search');
    var rows = document.getElementsByClassName('order-row');

    filterInput.addEventListener('input', function() {
      var filterValue = filterInput.value.toLowerCase();

      // Perform AJAX request
      var xhr = new XMLHttpRequest();
      var url = getOrderRouteUrl(filterValue);
      xhr.open('GET', url, true);

      xhr.onload = function() {
        if (xhr.status === 200) {
          var response = JSON.parse(xhr.responseText);
          var users = response.users;
          var formattedNames = response.formattedNames;

          var container = document.getElementById('order-details-container');
          container.innerHTML = ''; // Clear previous data

          if (users.length > 0) {
            users.forEach(function(user) {
              var html = `
                <dl class="row">
                  <dd class="col-sm-4">Order From</dd>
                  <dt class="col-sm-8">${user.org_slug}</dt>
                  <dd class="col-sm-4">Influencer Names</dd>
                  <dt class="col-sm-8">${formattedNames}</dt>
                  <dd class="col-sm-4">Payer Id</dd>
                  <dt class="col-sm-8">${user.payer_id}</dt>
                  <dd class="col-sm-4">Payment Id</dd>
                  <dt class="col-sm-8">${user.payment_id}</dt>
                  <dd class="col-sm-4">Order Value</dd>
                  <dt class="col-sm-8">${user.amount} ${user.currency}</dt>
                  <dd class="col-sm-4">Order Status</dd>
                  <dt class="col-sm-8">${user.payment_status}<br></dt>
                  <dd class="col-sm-4">Order Date</dd>
                  <dt class="col-sm-8">${user.created_at}<br></dt>
                  <dd class="col-sm-4"></dd>
                  <dt class="col-sm-8">
                    <button type="button" class="btn btn-lg btn-secondary view-button" data-id="${user.id}">
                      Influencer Tasks
                    </button>
                  </dt>
                </dl>
                <dl class="row"></dl>
                <hr>
              `;
              container.innerHTML += html;
            });
          } else {
            container.innerHTML = 'No results found.';
          }
        }
      };

      xhr.send();
    });

    function getOrderRouteUrl(filterValue) {
      var baseUrl = "{{ route('myorder_search') }}";
      var encodedFilterValue = encodeURIComponent(filterValue);
      return baseUrl + '?search=' + encodedFilterValue;
    }
  });
</script>

Hopefully, It Will Help You !!!!