I am trying to create a search feature for my back-end in Laravel 4 , where I can search for users by ( firstname , lastname , email). I have this function so far but it's not really working :
public function searchUser()
{
$search = Input::get('search');
$searchTerms = explode(' ', $search);
foreach($searchTerms as $term)
{
$query = User::Where('firstname', 'LIKE', '%'. $term .'%');
}
$results = $query->get();
}
How do I get the others like lastname, email in there?
You can do this:
<?php
public function searchUser()
{
$search = Input::get('search');
$searchTerms = explode(' ', $search);
$query = User::query();
$fields = array('first_name', 'last_name', 'email');
foreach ($searchTerms as $term)
{
foreach ($fields as $field)
{
$query->orWhere($field, 'LIKE', '%'. $term .'%');
}
}
$results = $query->get();
}
This way it will do a LIKE query of all search terms in all fields.
You also can paginate it by doing:
$result = $query->paginate(10);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With