0
public function searchBook(Request $request, $dep, $bTitleAuthor)
{
   if($request->ajax()) {
       $books = Book::where('department_id', $dep)
       ->where(function($query) {
           $query->where('title', 'like', '%'.$bTitleAuthor.'%')
           ->orWhere('author', 'like', '%'.$bTitleAuthor.'%');
       });
   }
}

This is what i saw on Laravel page, but in their example they used raw values. I am using parameters from the function and $bTitleAuthor giving me error that it is an "undefined variable".

In the end, I want to achieve something like this:

SELECT * FROM books
WHERE department_id = '$dep' 
AND (
    WHERE title LIKE '$bTitleAuthor' 
    OR author LIKE '$bTitleAuthor'
);
IGP
  • 14,160
  • 4
  • 26
  • 43
Benjiro
  • 101
  • 2
  • 14

1 Answers1

1

With anonymous functions, you need to indicate you want to use a variable from outside the scope:

$books = Book::where('department_id', $dep)
  ->where(function($query) use ($bTitleAuthor) {
    $query->where('title', 'like', '%'.$bTitleAuthor.'%')
    ->orWhere('author', 'like', '%'.$bTitleAuthor.'%');
  });

Learn more about anonymous functions: https://www.php.net/manual/en/functions.anonymous.php

Greg
  • 5,862
  • 1
  • 25
  • 52
Jeremy Harris
  • 24,318
  • 13
  • 79
  • 133