Kastriot Kosumi
Kastriot Kosumi

Reputation: 47

Eloquent search in two columns using like

Hi guys can somebody help me

I need to search for users in a table from an text input

i did it if we search just by the name or by the last name but cant do it if we write both the name and the last name in the text input

this is the code when we write just the name or the last name:

$data = User::where('name', 'LIKE', '%'. $search .'%')
                 ->orWhere('firstname', 'LIKE', '%'. $search .'%')
                 ->get();

i think its something like this but it doesn't work :D

first i did split the text given from the input here is the code

$words = explode(' ', $search);
    $firstword = $words[0];
    $lastword = $words[1];


$data = User::where('name', 'LIKE', '%'. $firstword .'%')
                       ->where('firstname', 'LIKE', '%'. $lastword .'%')
                       ->get();

Upvotes: 1

Views: 2610

Answers (3)

Jasbin Karki
Jasbin Karki

Reputation: 614

) you can do something like this

$posts = Post::where('COLUMN_ONE','SEARCH STRING')->orWhere('COLUMN_TWO','LIKE','%'.$search)->paginate(2);

hope this helps

Upvotes: 0

Mahdi Youseftabar
Mahdi Youseftabar

Reputation: 2352

your problem was this (orWhere instead where):

$data = User::orWhere('name', 'LIKE', '%'. $firstword .'%')
                       ->orWhere('firstname', 'LIKE', '%'. $lastword .'%')
                       ->get();

Upvotes: 1

Jonathon
Jonathon

Reputation: 16283

You could do something like this to search for all the words against both the first name and last name columns:

// Get the search terms and define the columns we're looking at
$terms = explode(' ', $search);
$columns = ['firstname', 'lastname'];

// Start with an initial null query. I'm pretty sure Laravel expects a where before an orWhere, so this is an alright way to make that check.
$query = null;

// For each of the search terms
foreach ($terms as $term) {
    // For each column
    foreach ($columns as $column) {
        // If we have not yet started a query, start one now by applying a where to the User model. If we have started a query i.e. $query is not null, then use an orWhere
        if (is_null($query)) {
            $query = User::where($column, 'LIKE', '%' . $term . '%');
        } else {
            $query->orWhere($column, 'LIKE', '%' . $term . '%');
        }
    }
}

// Finally, get the results
$results = $query->get();

Upvotes: 3

Related Questions