I've the below function -
public function search_profile(Request $request)
{
$search_keyword = $request->search;
$search_user = $request->user;
$user_public = User::where('username', $request->user)->first();
$tags_list = Tag::orderBy('tag', 'asc')->get();
$bookmarks = Bookmark::orderBy('created_at','desc')->where('bookmarker', $search_user)->where('public', '1')->where('tags', 'rlike', $search_keyword)->orwhere('title', 'rlike', $search_keyword)->orwhere('description', 'rlike', $search_keyword)->orwhere('contents', 'rlike', $search_keyword)->paginate(15);
$bookmarks_all = Bookmark::orderBy('created_at','desc')->where('bookmarker', $search_user)->where('public', '1')->where('tags', 'rlike', $search_keyword)->orwhere('title', 'rlike', $search_keyword)->orwhere('description', 'rlike', $search_keyword)->orwhere('contents', 'rlike', $search_keyword)->get();
return view('profile_search')->with('bookmark', $bookmarks)->with('tags_list', $tags_list)->with('bookmarks_all', $bookmarks_all)->with('username', $user_public)->with('search_keyword', $search_keyword);
}
But I'm getting results even from other bookmarker
. For example - If $search_keyword = 'laravel'
and $serach_user = 'zack'
. I'm getting results from other users as well.
I'm new on laravel. So What I'm doing wrong in the queries?
Your query
$bookmarks = Bookmark::orderBy('created_at','desc')->where('bookmarker', $search_user)->where('public', '1')->where('tags', 'rlike', $search_keyword)->orwhere('title', 'rlike', $search_keyword)->orwhere('description', 'rlike', $search_keyword)->orwhere('contents', 'rlike', $search_keyword)->paginate(15);
will yield you something like this
SELECT * FROM bookmarks WHERE bookmarker = $search_user AND public = 1 OR title rlike $search_keyword OR content rlike $search_keyword;
Which is not what you intended since if it matches the title, it will return the result.
What you most likely want is this:
Bookmark::orderBy('created_at','desc')
->where('bookmarker', '$search_user')
->where('public', '1')
->orWhere(function ($query) use ($search_keyword) {
$query->where('title', 'rlike', $search_keyword)
->where('contents', 'rlike', $search_keyword);
})
->get();
Check out the advance where.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With