user9330768
user9330768

Reputation:

Laravel searching with like

I want to search the whole table, the way I have it now is it searches a certain column in the table. How can I search everything from the table instead of a certain column in the table? Here is my code if you need to see it

    $userinput=$request->input('mywhat');

    $userinputt=$request->input('mywhere');

    $str = trim(preg_replace('/\s+/',' ', $userinput));

    $strr = trim(preg_replace('/\s+/',' ', $userinputt));


    $this->validate($request,array(
       $userinputt=>'nullable',
    ));

   $pro=Profile::Where('what','Like','%'.$str.'%')->Where(function ($query) use($strr, $userinputt) {
    $query->Where('location', 'LIKE', '%'.$userinputt.'%');
    })->inRandomOrder()->paginate(15);



    return view('layouts.reveal')->with('pro',$pro);

Upvotes: 1

Views: 628

Answers (3)

user320487
user320487

Reputation:

You could try something like the following:

$query = Profile::select('*');

foreach((new Profile)->attributesToArray() as $column)
{
  $query->where($column, 'like', "%$search_value%");
}

$models = $query->get();

Performance will become a problem as your data set grows, however. You may want to consider a solution such as Laravel Scout, which offers full text search on eloquent models.

This works by indexing the entire toArray form of a model as they are created/updated by default. You can leverage Queues for further performance benefits.

Then your searchs are simplified to:

$models = App\Model::search('Search Term')->get();

Upvotes: 0

Sapnesh Naik
Sapnesh Naik

Reputation: 11656

There is no shortcut with like,

You can try with MATCH():

$pro = Profile:whereRaw("MATCH(`name`, `foo`, `bar`) AGAINST ('$search')");

but you can use nicolaslopezj/searchable package it is easy and customizable and it also supports joins.

Upvotes: 1

Nikola Gavric
Nikola Gavric

Reputation: 3543

Something like this might help:

$attributes = $profile->attributes;
$query = null;
foreach($attributes as $attribute) {
    if(!$query) {
        $query = Profile::where($attribute, 'like', '%'.$searchTerm.'%');
    } else {
        $query = $query->orWhere($attribute, 'like', '%'.$searchTerm.'%');
    }
}
$results = $query->get();

I do not recommend the above code for any production usage, but instead you can use already finished OS libraries like Searchy or others.

Upvotes: 0

Related Questions