skip to Main Content

I want to search the book with the Author’s Name. if the author is F. U. Umesh I passed F. U. Umesh then it works fine. But, When I Pass without . like: F U Umesh. No, Result was found. code on Controller like this:

$data['books'] = BookMaster::select('id', 'code', 'title', 'image', 'categories', 'author', 'publisher', 'status')
            ->where(function ($query) use ($request) {
                if ($request->has('author')) {
                    $query->where('author', 'like', '%'.$request->author.'%');
                    $this->filter_query['author'] = $request->author;
                }
            })
            ->orderBy('code','asc')
            ->get();

If you have an idea about that Please guide me.
I need to search without . like: F U Umesh.

2

Answers


  1. Try with these 2 codes

    1.

    $data['books'] = BookMaster::select('id', 'code', 'title', 'image', 'categories', 'author', 'publisher', 'status')
                ->where(function ($query) use ($request) {
                    if ($request->has('author')) {
                        $query->where('author', 'LIKE', str_replace(' ', '%', $request->author));
                        $this->filter_query['author'] = $request->author;
                    }
                })
                ->orderBy('code','asc')
                ->get();
    

    or use this

    $data['books'] = BookMaster::select('id', 'code', 'title', 'image', 'categories', 'author', 'publisher', 'status')
                    ->where(function ($query) use ($request) {
                        if ($request->has('author')) {
                            $query->->whereRaw('author REGEXP ?', [str_replace(' ', '\.? ', $request->author)]);
                            $this->filter_query['author'] = $request->author;
                        }
                    })
                    ->orderBy('code','asc')
                    ->get();
    
    Login or Signup to reply.
  2. That is expected behavior. You’d need to add a specific WHERE clause to that SQL query. Something like

    WHERE REPLACE(author, ".", "") LIKE %...%

    But if you want to keep both behaviors, adding an orWhere could work.

    if ($request->has('author')) {
        $query->where('author', 'like', '%'.$request->author.'%')
              ->orWhereRaw('REPLACE(author, ".", "") LIKE %?%', [$request->author]);
              //->orWhere(DB::raw('REPLACE(author, ".", "")', 'like', "%$request->author%");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search