Implementing Multi-Search with Multiple Query Functionality in Laravel

We will explore how to implement multi-search functionality with multiple-query support in Laravel. Searching is a common requirement in many web applications, and allowing users to perform multiple searches with different criteria can enhance the user experience and provide more targeted results. We will leverage the power of Laravel’s query builder and build a robust search feature that enables users to execute multiple queries simultaneously. Let’s dive in!

Step 1:- HTML Part

<div class="col-6 py-3 px-3 p-3">
                    <label class="font-weight-bold text-danger">Social Site</label>
                    <select class="form-control" name="filter_by_socialsite[]" id="filter_by_socialsite" multiple style="font-size: 18px; border: 1px solid blue;">
                        <option value="facebook"><b>Facebook</b></option>
                        <option value="twitter"><b>Twitter</b></option>
                        <option value="youtube"><b>Youtube</b></option>
                        <option value="wordpress"><b>WordPress</b></option>
                        <option value="tumblr"><b>Tumblr</b></option>
                        <option value="instagram"><b>Instagram</b></option>
                        <option value="quora"><b>Quora</b></option>
                        <option value="pinterest"><b>Pinterest</b></option>
                        <option value="reddit"><b>Reddit</b></option>
                        <option value="koo"><b>Koo</b></option>
                        <option value="scoopit"><b>Scoopit</b></option>
                        <option value="slashdot"><b>Slashdot</b></option>
                        <option value="roposo"><b>Roposo</b></option>
                        <option value="chingari"><b>Chingari</b></option>
                        <option value="telegram"><b>Telegram</b></option>
                        <option value="linkedin"><b>Linkedin</b></option>
                        <option value="linkedin_grp"><b>Linkedin Group</b></option>
                        <option value="fb_grp"><b>Facebook Group</b></option>
                        <option value="mitron"><b>Mitron</b></option>
                    </select>
                </div>

Step 2:- Javascript With Ajax and make a route

<script type="text/javascript">
    $(document).ready(function() {
        var currentPage = parseInt('{{ $filteredData->currentPage() }}'); // Get the current page from the server-side variable

        $('#filter_by_socialsite').on('change', function() {
            var filter_by_socialsite = $(this).val();
            console.log(filter_by_socialsite);
            currentPage = 1; // Reset the current page to 1 when the filter changes
            fetch_social_data(filter_by_socialsite, currentPage);
            updateURL(currentPage);
        });

        $('#filter_by_socialsite').select2({
            tags: true,
            tokenSeparators: [',', ' '],
            placeholder: 'Select By Social Site',
            width: '100%',
        }).on('select2:close', function(e) {
            var selectedValue = $(this).val(); // Get the selected value
            if (selectedValue === null || selectedValue.length === 0) {
                location.reload(); // Refresh the page if the selected value is null or blank
            }
        }).on('select2:unselect', function(e) {
            var selectedValue = $(this).val(); // Get the selected value
            if (selectedValue === null || selectedValue.length === 0) {
                location.reload(); // Refresh the page if the selected value is null or blank
            }
        });

        $(document).on('click', '.previous_button', function(e) {
            e.preventDefault();
            var filter_by_socialsite = $('#filter_by_socialsite').val();
            if (currentPage > 1) {
                currentPage--; // Decrement the current page by 1 if it's greater than 1
                fetch_social_data(filter_by_socialsite, currentPage);
                updateURL(currentPage);
            }
        });

        $(document).on('click', '.next_button', function(e) {
            e.preventDefault();
            var filter_by_socialsite = $('#filter_by_socialsite').val();
            currentPage++; // Increment the current page by 1
            fetch_social_data(filter_by_socialsite, currentPage);
            updateURL(currentPage);
        });

        function fetch_social_data(filter_by_socialsite, page, search_query) {
            console.log('fetch_social_data function is called');
            $('#user_pic_file').html('');
            var cleanPage = page.toString().replace('amp;', '');
            $.ajax({
                url: "/welcome_influencersocialsite",
                method: "GET",
                data: {
                    filter_by_socialsite: filter_by_socialsite.join(','),
                    page: cleanPage,
                    search_query: search_query // Include the search query parameter
                },
                success: function(data) {
                    console.log(data + ' - Data in success function');
                    $('#user_pic_file').html('');
                    $('#user_pic_file').html(data);
                    var dataCount = $('#count-data').find('.data-item').length; // Update dataCount based on the length of the received data
                    togglePaginationButtons(dataCount); // Call the function to toggle pagination buttons visibility and pass dataCount
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error('AJAX request failed: ' + textStatus, errorThrown);
                }
            });
        }

        $('#search_query').on('input', function() {
            var searchQuery = $('#search_query').val(); // Get the value of your search input field
            if (searchQuery) {
                $('.pagination-buttons').show(); // Show the pagination buttons if there is a search query
            } else {
                $('.pagination-buttons').hide(); // Hide the pagination buttons if there is no search query
            }
        });

        function updateURL(page) {
            var newURL = window.location.href.split('?')[0] + '?page=' + page;
            window.history.replaceState({}, '', newURL);
        }

        function togglePaginationButtons(dataCount) {
            var searchQuery = $('#search_query').val(); // Get the value of your search input field
            var selectedSocialSites = $('#filter_by_socialsite').val(); // Get the selected social sites
            var currentPage = parseInt('{{ $filteredData->currentPage() }}'); // Get the current page from the server-side variable
            var totalPages = parseInt('{{ $filteredData->lastPage() }}'); // Get the total number of pages from the server-side variable

            // Hide the "Previous" button on the first page
            if (currentPage === 1) {
                $('.previous_button').hide();
            } else {
                $('.previous_button').show();
            }

            // Show or hide the "Next" button based on the current page and total pages
            if (currentPage >= totalPages || dataCount <= 1) {
                $('.next_button').hide(); // Hide the "Next" button if it's the last page or if there are 1 or fewer data
            } else if (searchQuery || currentPage < totalPages) {
                $('.next_button').show(); // Show the "Next" button if there is a search query or if the current page is less than the total pages
            }

            // Show or hide the "Previous" button based on the current page and total pages
            if (currentPage === totalPages || dataCount <= 1) {
                $('.previous_button').show(); // Show the "Previous" button if it's the last page or if there are 1 or fewer data
            } else {
                $('.previous_button').hide(); // Hide the "Previous" button if it's not the last page
            }

        }


        // Call togglePaginationButtons initially
        togglePaginationButtons();
    });
</script>

Step 3:- Controller Function

  public function influencersocialsite(Request $request)
    {
        Log::info('Inside influencersocialsite method');
        Log::info($request);
        $searchsocial = $request->get('filter_by_socialsite');
        $page = $request->input('page');
        Log::info($searchsocial . 'roshan search fetchsocialsitedata ka data hai');
        $filterBySocialSite = $searchsocial;
        $search = '';

        $search = str_replace('', '%', $searchsocial);
        $searchArray = explode(',', $filterBySocialSite);
        if (is_string($filterBySocialSite)) {
            $filterBySocialSite = explode(',', $filterBySocialSite);
        }
        if (!empty($searchArray)) {
            log::info('payments aata hai if ke andar');
            $data = DB::connection('payments')
                ->table('addprofiles')
                ->leftJoin('countries', 'addprofiles.country_id', '=', 'countries.country_id')
                ->leftJoin('states', 'addprofiles.state_id', '=', 'states.state_id')
                ->leftJoin('cities', 'addprofiles.city_id', '=', 'cities.city_id')
                ->leftJoin('users', 'addprofiles.user_id', '=', 'users.id')
                ->leftJoin('payments', 'payments.admin_id', '=', 'addprofiles.user_id')
                ->select('addprofiles.*', 'countries.country_name', 'states.state_name', 'cities.city_name', 'addprofiles.file_pic', 'payments.admin_id');

            foreach ($filterBySocialSite as $socialSite) {
                switch ($socialSite) {
                    case 'facebook':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.face_price) AS face_price");
                        break;
                    case 'twitter':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.twitter_price) AS twitter_price");
                        break;
                    case 'youtube':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.youtube_price) AS youtube_price");
                        break;
                    case 'wordpress':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.wordpress_price) AS wordpress_price");
                        break;
                    case 'tumblr':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.tumblr_price) AS tumblr_price");
                        break;
                    case 'instagram':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.instagram_price) AS instagram_price");
                        break;
                    case 'quora':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.quora_price) AS quora_price");
                        break;
                    case 'pinterest':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.pinterest_price) AS pinterest_price");
                        break;
                    case 'reddit':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.reddit_price) AS reddit_price");
                        break;

                    case 'koo':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.koo_price) AS koo_price");
                        break;
                    case 'scoopit':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.scoopit_price) AS scoopit_price");
                        break;
                    case 'slashdot':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.slashdot_price) AS slashdot_price");
                        break;
                    case 'roposo':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.roposo_price) AS roposo_price");
                        break;
                    case 'chingari':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.chingari_price) AS chingari_price");
                        break;
                    case 'telegram':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.telegram_price) AS telegram_price");
                        break;
                    case 'linkedin':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.linkedin_price) AS linkedin_price");
                        break;
                    case 'linkedin_grp':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.linkedin_grp_price) AS linkedin_grp_price");
                        break;
                    case 'fb_grp':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.fb_grp_price) AS fb_grp_price");
                        break;
                    case 'mitron':
                        $data->selectRaw("GROUP_CONCAT(DISTINCT payments.mitron_price) AS mitron_price");
                        break;
                        // Add cases for remaining social sites
                }
            }

            $results = $data->where(function ($query) use ($filterBySocialSite) {
                foreach ($filterBySocialSite as $socialSite) {
                    switch ($socialSite) {
                        case 'facebook':
                            $query->orWhereNotNull('payments.face_price');
                            break;
                        case 'twitter':
                            $query->orWhereNotNull('payments.twitter_price');
                            break;
                        case 'youtube':
                            $query->orWhereNotNull('payments.youtube_price');
                            break;
                        case 'wordpress':
                            $query->orWhereNotNull('payments.wordpress_price');
                            break;
                        case 'tumblr':
                            $query->orWhereNotNull('payments.tumblr_price');
                            break;
                        case 'instagram':
                            $query->orWhereNotNull('payments.instagram_price');
                            break;
                        case 'quora':
                            $query->orWhereNotNull('payments.quora_price');
                            break;
                        case 'pinterest':
                            $query->orWhereNotNull('payments.pinterest_price');
                            break;
                        case 'reddit':
                            $query->orWhereNotNull('payments.reddit_price');
                            break;
                        case 'koo':
                            $query->orWhereNotNull('payments.koo_price');
                            break;
                        case 'scoopit':
                            $query->orWhereNotNull('payments.scoopit_price');
                            break;
                        case 'slashdot':
                            $query->orWhereNotNull('payments.slashdot_price');
                            break;
                        case 'roposo':
                            $query->orWhereNotNull('payments.roposo_price');
                            break;
                        case 'chingari':
                            $query->orWhereNotNull('payments.chingari_price');
                            break;
                        case 'telegram':
                            $query->orWhereNotNull('payments.telegram_price');
                            break;
                        case 'linkedin':
                            $query->orWhereNotNull('payments.linkedin_price');
                            break;
                        case 'linkedin_grp':
                            $query->orWhereNotNull('payments.linkedin_grp_price');
                            break;
                        case 'fb_grp':
                            $query->orWhereNotNull('payments.fb_grp_price');
                            break;
                        case 'mitron':
                            $query->orWhereNotNull('payments.mitron_price');
                            break;
                            // Add cases for remaining social sites
                    }
                }
            })
                ->groupBy('payments.id') // Replace 'your_table_name.id' with the appropriate column names
                ->get();

            $data->where(function ($query) use ($searchArray) {
                foreach ($searchArray as $search) {
                    $query->where('addprofiles.user_id', 'like', '%' . $search . '%')
                        ->orWhere('addprofiles.user_name', 'like', '%' . $search . '%')
                        ->orWhere('countries.country_name', 'like', '%' . $search . '%')
                        ->orWhere('states.state_name', 'like', '%' . $search . '%')
                        ->orWhere('cities.city_name', 'like', '%' . $search . '%')
                        ->orWhere(function ($query) use ($search) {
                            $query->where(function ($query) use ($search) {
                                $query->where('addprofiles.facebook', 'like', '%' . $search . '%')
                                    ->orWhere(function ($query) {
                                        $query->whereNull('addprofiles.facebook')
                                            ->whereNotNull('payments.face_price');
                                    });
                            });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.twitter', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.twitter')
                                        ->whereNotNull('payments.twitter_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.youtube', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.youtube')
                                        ->whereNotNull('payments.youtube_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.wordpress', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.wordpress')
                                        ->whereNotNull('payments.wordpress_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.tumblr', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.tumblr')
                                        ->whereNotNull('payments.tumblr_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.instagram', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.instagram')
                                        ->whereNotNull('payments.instagram_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.quora', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.quora')
                                        ->whereNotNull('payments.quora_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.pinterest', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.pinterest')
                                        ->whereNotNull('payments.pinterest_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.reddit', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.reddit')
                                        ->whereNotNull('payments.reddit_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.koo', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.koo')
                                        ->whereNotNull('payments.koo_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.scoopit', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.scoopit')
                                        ->whereNotNull('payments.scoopit_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.slashdot', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.slashdot')
                                        ->whereNotNull('payments.slashdot_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.roposo', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.roposo')
                                        ->whereNotNull('payments.roposo_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.chingari', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.chingari')
                                        ->whereNotNull('payments.chingari_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.mitron', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.mitron')
                                        ->whereNotNull('payments.mitron_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.telegram', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.telegram')
                                        ->whereNotNull('payments.telegram_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.fb_grp', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.fb_grp')
                                        ->whereNotNull('payments.fb_grp_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.linkedin_grp', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.linkedin_grp')
                                        ->whereNotNull('payments.linkedin_grp_price');
                                });
                        })
                        ->orWhere(function ($query) use ($search) {
                            $query->where('addprofiles.linkedin', 'like', '%' . $search . '%')
                                ->orWhere(function ($query) {
                                    $query->whereNull('addprofiles.linkedin')
                                        ->whereNotNull('payments.linkedin_price');
                                });
                        });
                }
            });

            $data->groupBy('payments.admin_id');

            $data = $data->orderBy('addprofiles.user_id', 'desc')
                ->get();
            $perPage = 2;
            $filteredData = $data->filter(function ($item) {
                return !empty($item->facebook) || !empty($item->twitter) || !empty($item->youtube) || !empty($item->wordpress) || !empty($item->tumblr) || !empty($item->instagram) || !empty($item->quora) || !empty($item->pinterest) || !empty($item->reddit) || !empty($item->koo) || !empty($item->scoopit) || !empty($item->slashdot) || !empty($item->telegram) || !empty($item->fb_grp) || !empty($item->linkedin_grp) || !empty($item->linkedin) || !empty($item->roposo) || !empty($item->chingari) || !empty($item->mitron);
            });
            // Paginate the filtered data
            $currentPage = (int) request()->input('page', 1); // Cast the value to an integer and set a default value of 1 if not provided

            $filteredData = new Paginator(
                $filteredData->forPage($currentPage, $perPage),
                $filteredData->count(),
                [
                    'path' => Paginator::resolveCurrentPath(),
                    'pageName' => 'page',
                    'currentPage' => $currentPage, // Pass the currentPage parameter to the Paginator
                ],
                []
            );

            $previousPageUrl = $filteredData->previousPageUrl();
            $nextPageUrl = $filteredData->nextPageUrl();
            $search = 'social';

            // Get the previous and next page URLs

            Log::info($filteredData . '$data fetchjobsdata ka last addprofiles  data hai');
            // Pass the filtered data and pagination URLs to the view
            return view('paginatedsearch_data', compact('filteredData', 'search', 'nextPageUrl', 'previousPageUrl'))->render();
        } else {
            log::info('else payments aata hai if ke andar');
            $data = DB::table('addprofiles')
                ->leftJoin('countries', 'addprofiles.country_id', '=', 'countries.country_id')
                ->leftJoin('states', 'addprofiles.state_id', '=', 'states.state_id')
                ->leftJoin('cities', 'addprofiles.city_id', '=', 'cities.city_id')
                ->leftJoin('users', 'addprofiles.user_id', '=', 'users.id')
                ->select('addprofiles.*', 'countries.country_name', 'states.state_name', 'cities.city_name', 'addprofiles.file_pic')
                ->orderBy('id', 'desc')
                ->get();
            $filteredData = $data->filter(function ($item) {
                return !empty($item->facebook) || !empty($item->twitter) || !empty($item->youtube) || !empty($item->wordpress) || !empty($item->tumblr) || !empty($item->instagram) || !empty($item->quora) || !empty($item->pinterest) || !empty($item->reddit) || !empty($item->koo) || !empty($item->scoopit) || !empty($item->slashdot) || !empty($item->telegram) || !empty($item->fb_grp) || !empty($item->linkedin_grp) || !empty($item->linkedin) || !empty($item->roposo) || !empty($item->chingari) || !empty($item->mitron);
            });
            Log::info('$data fetchjobsdata ka last addprofiles  data hai');
            return view('paginated_data', compact('filteredData'))->render();
        }
    }

HopeFully, it will Help You !!!!

Related Posts

The Complete SEO Playbook for AI Guest Post Generation and Publishing

Introduction Search engine optimization relies heavily on authority, relevance, and trust. While search algorithms continually evolve, securing high-quality backlinks through strategic content placement remains a foundational ranking…

Read More

Top Digital Marketing Workflow Management Tools for Agencies

Introduction Managing a modern digital marketing stack often feels like juggling dozens of disconnected software subscriptions. Marketing managers, agency owners, and SEO specialists frequently find themselves jumping…

Read More

AI Prompt Management Tools: From Basic Prompts to High-Value Digital Assets

Generative artificial intelligence has fundamentally altered how modern enterprises, creative teams, and technical engineers operate. However, as organizations increase their reliance on large language models (LLMs), a…

Read More

Automated Payment Management Software for Modern Enterprises

Finance operations form the backbone of every enterprise, yet many organizations still struggle with fragmented billing tools, delayed collections, and manual reconciliation. Relying on spreadsheets and disconnected…

Read More

The Complete Guide to Choosing the Best Vehicle Rental Management Software

INTRODUCTION Managing a vehicle rental business manually through spreadsheets, paper ledgers, or messaging apps creates significant operational friction. Rental agency owners face recurring challenges including double bookings,…

Read More

The Ultimate Guide to Predictive Alerts and Data Observability

Introduction In modern data-driven enterprises, data pipelines serve as the central circulatory system of business intelligence, operational analytics, machine learning platforms, and executive decision-making. However, as data…

Read More
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x