Last active
June 20, 2022 01:58
-
-
Save akosiyawin/0075b31fba216188cc98217e7761a596 to your computer and use it in GitHub Desktop.
One way of doing dynamic search in all columns.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
private function searchConcats($query, $search) | |
{ | |
$query->orWhere(DB::raw('CONCAT(registrants.student_year,"-",LPAD(registrants.student_no,4,0))'), "LIKE", "%" . $search . "%"); | |
$query->orWhere(DB::raw('CONCAT(registrants.first_name," ",registrants.last_name)'), "LIKE", "%" . $search . "%"); | |
$query->orWhere(DB::raw('CONCAT(registrants.last_name," ",registrants.first_name)'), "LIKE", "%" . $search . "%"); | |
} | |
public function index(Request $request) { | |
//... Other Logics above ⬆️⬆️ | |
if ($request->searchIsNull) { | |
$query->when($validated['search'], function ($query, $search) { | |
$query->where(function ($query) use ($search) { | |
// Schema::getColumnListing("registrants"); //get all columns of table | |
$searchables = ["student_year", "student_no", "first_name", "middle_name", "last_name", "date_of_birth", "place_of_birth", "address", "course", "contact_no", "civil_status", "citizenship", "father_name", "father_occupation", "mother_name", "mother_occupation", "guardian_name", "relationship_to_guardian", "guardian_contact_no", "guardian_address", "elementary", "elementary_year_graduated", "high_school", "high_school_year_graduated", "college", "college_year_graduated", "email", "last_school_attended", "last_school_address", "image", "learning_reference_no", "year_level", "gender",]; | |
$values = explode(" ", $search); | |
foreach ($values as $value) { | |
foreach ($searchables as $searchable) { | |
$query->orWhere($searchable, "LIKE", "%" . $value . "%"); | |
} | |
} | |
$this->searchConcats($query, $search); | |
}); | |
}); | |
} | |
$registrants = $query->paginate(10); | |
//recursive call if there is no search results | |
if (!$registrants->count() && !$request->searchIsNull) { | |
$request = $request->merge(['searchIsNull' => 1]); | |
return $this->index($request); | |
} | |
return RegistrantResource::collection($registrants); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment