1

I am trying to implement search in Laravel. I want to search on models. Since there can be many records in the database, I am trying the chunk function.

public function searchLeads($param)
    {
        $results = array();

        // get all leads
        Lead::chunk(100, function($leads) use ($results, $param) {
            // search in name
            $results = array_merge($results, $this->repository->searchInName($leads, $param));

            // search in email
            $results = array_merge($results, $this->repository->searchInEmail($leads, $param));

           // and so on ...
    }

    // eliminate duplicates
    $collection = collect($results);
    $collection = $collection->unique();

    $results = $collection->all();

    dd($results);
    // return $results;
}

Note: The searchIn... functions return array of results and are working as expected.

When I try the above code, I get an empty array. So I changed the following line (added a reference & to $results).

Lead::chunk(100, function($leads) use (&$results, $param) {

Now I get the expected output.

My question is, have I stumbled upon the right solution, or am I missing something that might introduce bugs in the code?

Note: I know using where clause is a better and efficient way; but I cannot use where for this.

2 Answers 2

1

I got the solution after reading a bit about php closures. My real worry was that I am not using the $results array correctly.

But after reading php docs, I know I am doing it correctly.

Please note that I am aware of where clause and it's usage would be much more efficient here. But that's not what I was trying to ask.

Sign up to request clarification or add additional context in comments.

Comments

0

to use the search, you could do something like:

$results = Lead::where('mail','like', $param)->orWhere('name','like', $param)->get(); 

then mysql does the search, which i believe is the fastes way of doing it.

depending on how the search should be done:

...where('mail','like', %$param%)...

https://laravel.com/docs/5.1/queries#where-clauses

else try to describe what the end goal of your search is?

1 Comment

What you suggest is correct. But that's not what I wanted to ask. It's my fault; I didn't clarify myself in the question. I cannot use where clauses as the search is being conducted on derived and related fields which cannot be directly converted to an SQL query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.