Gen Fa
Gen Fa

Reputation: 65

How to filter in particular records in laravel?

I'm trying to do a search but problem is I can search in whole table not only in those records I fetched in first place!

public function getAllReceivedNotifies($request){

    $notifies = Notify::with('sender','sender.role')
                ->where('receiver_id', auth()->user()->id)
                ->orderBy('created_at', 'DESC');

    if ($request->has('q')) {
        $notifies->where('reason', 'LIKE', "%" . $request->get('q') . "%");
        $notifies->orWhere('comment', 'LIKE', "%" . $request->get('q') . "%");
        $notifies->orWhere('created_at', 'LIKE', "%" . $request->get('q') . "%");
    }
    return $notifies->paginate();
}

Upvotes: 0

Views: 45

Answers (1)

N69S
N69S

Reputation: 17206

you need to put the three string search in parenthesis, you do that by grouping them into where() in eloquent

public function getAllReceivedNotifies($request){

    $notifies = Notify::with('sender','sender.role')
            ->where('receiver_id', auth()->user()->id)
            ->orderBy('created_at', 'DESC');

    if ($request->has('q')) {
        $notifies->where(function ($query) {
            $query->where('reason', 'LIKE', "%" . $request->get('q') . "%");
            $query->orWhere('comment', 'LIKE', "%" . $request->get('q') . "%");
            $query->orWhere('created_at', 'LIKE', "%" . $request->get('q') . "%");
        });
    }
    return $notifies->paginate();
}

Upvotes: 1

Related Questions