Skip to content

Instantly share code, notes, and snippets.

@clouddueling
Created February 16, 2013 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save clouddueling/4967617 to your computer and use it in GitHub Desktop.
Save clouddueling/4967617 to your computer and use it in GitHub Desktop.
search table with like using eloquent
public static function search_contacts($terms)
{
$search_all = ! Input::has('first') && ! Input::has('last');
$terms = escape($terms);
$search_terms = explode(' ', $terms);
$search_term_bits = array();
foreach ($search_terms as $term) {
$term = trim($term);
if (! empty($term)) {
if ((Input::has('first') && Input::has('last')) || $search_all)
$search_term_bits[] = "`first` LIKE '{$term}%' OR `last` LIKE '{$term}%'";
if (Input::has('first') && ! Input::has('last'))
$search_term_bits[] = "`first` LIKE '{$term}%'";
if (! Input::has('first') && Input::has('last'))
$search_term_bits[] = "`last` LIKE '{$term}%'";
}
}
$contacts = Contact::raw_where("(" . implode(' AND ', $search_term_bits) . ")")
->raw_where("`account_user_id`=?", array(Auth::user()->account_user_id))
->where_deleted(0)
->take(20)
->get();
$contacts_array = array();
foreach ($contacts as $contact) {
$new_contact = $contact->to_array();
$new_contact['rank'] = levenshtein($terms, $contact->first . ' ' . $contact->last);
$contacts_array[] = $new_contact;
}
aasort($contacts_array, 'rank');
return $contacts_array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment