Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a search feature in Laravel 4

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?

like image 235
user3150060 Avatar asked Dec 09 '25 03:12

user3150060


1 Answers

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);
like image 172
Antonio Carlos Ribeiro Avatar answered Dec 10 '25 17:12

Antonio Carlos Ribeiro