Search code examples
phplaravellaravel-5.5laravel-5.6

Global search with laravel


I wrote a code to search in within a data table whereby entering a id and customer name but i need to search extra field without specifying the column.

I need to search by column, there's the controller with Search function:

public function search(Request $request)
    {

        if ($request->ajax()) {

            $output = "";
            $indents = DB::table('indents')
                ->where('id', 'LIKE', '%' . $request->search . '%')
                ->orwhere('customer_name', 'LIKE', '%' . $request->search . '%')
                ->orwhere('*', 'LIKE', '%'.$request->search. '%')
                ->get();
                $count=1;
            foreach ($indents as $key => $indent) {


                    $output .= '<tr>' .
                    '<td>'.$count++.'</td>'.
//                    '<td>' . $indent->id . '</td>' .
                    '<td>' . $indent->customer_name . '</td>' .
                    '<td>' . $indent->phone_no . '</td>' .
                    '<td>' . $indent->date_of_delivery . '</td>' .
                    '<td>' . $indent->delivery_at . '</td>' .
                    '<td>' . '.<a href="' . route('edp.show', $indent->id) . '">.' . '<img src="assets/images/select.jpg" class="imgsize">.' . '</a>.' . '</td>' .
                    '</tr>';

            }
            return Response($output);
        }

    }

Solution

  • You can have an array of columns to search in like this:

    $columnsToSearch = ['column1', 'column2', 'column3'];

    These columns can be part of the $request if you need it to be passed from the frontend/api.

    Then loop through each $columnsToSearch and add to your query builder like so:

    $columnsToSearch = ['column1', 'column2', 'column3'];
    // or $columnsToSearch = $request->input('columns_to_search');
    
    $searchQuery = '%' . $request->search . '%';
    
    $indents = DB::table('indents')
                ->where('id', 'LIKE', $searchQuery);
    
    foreach($columnsToSearch as $column) {
        $indents = $indents->orWhere($column, 'LIKE', $searchQuery);
    }
    
    $indents = $intents->get();