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
  • 10,505
  • 3
  • 19
  • 35
Benjiro
  • 91
  • 1
  • 12

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

Grzegorz
  • 5,219
  • 1
  • 27
  • 48
Jeremy Harris
  • 23,837
  • 13
  • 78
  • 128