$dataQuery = $dataQuery->where(function ($query) use ($fullname) {
$nameParts = explode(' ', $fullname);
if (count($nameParts) === 2) {
$query->where(function ($q) use ($nameParts) {
$q->where('users.firstname', 'like', '%' . $nameParts[0] . '%')
->where('users.lastname', 'like', '%' . $nameParts[1] . '%');
});
} else {
$query->where(function ($q) use ($fullname) {
$q->where('users.firstname', 'like', '%' . $fullname . '%')
->orWhere('users.lastname', 'like', '%' . $fullname . '%');
});
}
});
I attempted to filter users based on a full name using a query that includes both firstname and lastname, as well as their concatenation. My goal was to allow users to search by their full name, where the search term could be matched against either firstname, lastname, or both combined
2
Answers
You can modify your query to handle both the individual parts of the name and their concatenation. Here’s a refined approach:
});
Use this code inside if and else condition then
->orWhere(DB::raw("CONCAT(users.firstname, ‘ ‘, users.lastname)"), ‘like’, "%$your_variable_name%");