public function search(Request $request)
    {
        $result = ['status' => 200];

        try{
        $categories = $request['categories'];
        $searchCategories = explode(',', $categories);

          $searchValues = Post::all();
          $dataSearch = [];

          foreach ($searchCategories as $searchCategory) { 
          foreach($searchValues as $searchValue){
             if(!isset($categories)) {
                    $dataSearch[] = $searchValue;
                } else {    
                $searchValuesTrim = trim($searchValue->categories, '""');
                $searchValuesExplode = (explode(',',$searchValuesTrim ));
                foreach($searchValuesExplode as $searchValuesKey){
                    if (preg_match('/' . $searchValuesKey . '/', $searchCategory)) {
                            if (!in_array($searchValue, $dataSearch)) {
                                $dataSearch[] = $searchValue;
                            }
                        }
                    }
                }
            } 
         }
            $result['dataSearch'] =  $dataSearch;
        } catch (Exception $e) {
            $result = [
                'status' => 500,
                'error' => $e->getMessage()
            ];
        }

        return response()->json($result,  $result['status']);
    }

$categories = $request[‘categories’]; – get the values to search

$searchCategories = explode(‘,’, $categories); – Since $categories is a string, we have to convert it to an array. We use explode for conversion.

$searchValues = Post::all(); – Getting the data from the database

$dataSearch = []; – initializing dataSearch

**foreach ($searchCategories as $searchCategory) { **– iterate over arrays for $searchCategories

foreach($searchValues as $searchValue){ – iterate over arrays from searchValues in database

if(!isset($categories)) { $dataSearch[] = $searchValue; – if $categories is not being set, so we display all

$searchValuesTrim = trim($searchValue->categories, ‘””‘); – get $categories data from the database and trim “”

$searchValuesExplode = (explode(‘,’,$searchValuesTrim )); – result is a string, so we need to convert it to an array

foreach($searchValuesExplode as $searchValuesKey){ – iterate over arrays

if (preg_match(‘/’ . $searchValuesKey . ‘/’, $searchCategory)) { – use preg_match to perform a regular expression match. If $searchCategory is in $searchValuesKey

if (!in_array($searchValue, $dataSearch)) { – check if $searchValues already exists in $dataSearch to avoid repetition of data

$dataSearch[] = $searchValue; – store the $searchValue in $dataSearch[]