skip to Main Content
$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


  1. You can modify your query to handle both the individual parts of the name and their concatenation. Here’s a refined approach:

    $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] . '%');
        })->orWhereRaw("CONCAT(users.firstname, ' ', users.lastname) like ?", ['%' . $fullname . '%']);
    } else {
        $query->where(function ($q) use ($fullname) {
            $q->where('users.firstname', 'like', '%' . $fullname . '%')
              ->orWhere('users.lastname', 'like', '%' . $fullname . '%')
              ->orWhereRaw("CONCAT(users.firstname, ' ', users.lastname) like ?", ['%' . $fullname . '%']);
        });
    }
    

    });

    Login or Signup to reply.
  2. Use this code inside if and else condition then

    ->orWhere(DB::raw("CONCAT(users.firstname, ‘ ‘, users.lastname)"), ‘like’, "%$your_variable_name%");

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search