Laravel search function query builder

Viewed 1611

I am trying to write a function which handles a search query for my website

I have a field called 'unique' which has a true or false value for this search. Because this page will be listing non unique results i need it as e.g 'unique' , '!=', true

i have 2 other fields name, description so when you search it returns the expected results

I have written the below code but if i click search on the page it will list all the results regardless if the unique field is true or false and if i search for a name or description that returns results ignoring the unique.

    $films = Film::when($request->input('unique'), function ($query) {
        $query->where('unique', '!=', true);
    })
        ->where('name', 'like', "%$search%")
        ->orWhere('description', 'like', "%$search%")
        ->get();

Im not very knowlegable when it comes to eloquent queries so i maybe missing something here.

Summarise functionality i need: If i search without entering in the search box field only return records that have unique as TRUE and if i search for a name or description in the text field only return records that match the input and with the unique being TRUE.

Any feedback would be great, thanks!

2 Answers

I'm not sure if I got your question, but might this be a solution to your problem:

$filmQuery = Film::where('unique', false);
if($search !== "") {
   $filmQuery = $filmQuery->where(function ($query) {
       $query->where('name', 'like', "%$search%")
       ->orWhere('description', 'like', "%$search%");
   });
}
$films = $filmQuery->get();    

This should get you all the Films, where either 'name' or 'description' match your $search and which also have 'unique' === false.

And if $search === "" (empty) you should get all the films where 'unique' === false.

I'm not sure if I got your question, but might this be a solution to your problem:

$id = $request->id;
$search = $request->search;

$data = DB::table('invoice');
$data = $data->select('*');
if($search !== "") {
  $data = $data->where('id', '=', $id);
}
$data = $data->get();
Related