Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to search clients of the authenticated user?

I have a categorization in DB that a user has some clients, they are connected by user_id. At me, tables are shown in the dashboard that comes only clients that are registered by the currently logged-in user, but when I search by name or surname or mail at the table I see clients of other users.
This is the code?

public function render()
    {
        $user = Auth::user()->id;
        if($this->searchTerm == ''){
            return view('livewire.dashboard.user-management', [
                'clients' => Client::where('user_id', '=', $user)->orderBy($this->sortField, $this->sortAsc)->paginate(8)
            ]);
        }
        else{
            return view('livewire.dashboard.user-management', [
                'clients' => Client::where('user_id', '=', $user)
                ->where('name', 'LIKE', '%'.$this->searchTerm.'%')
                ->orWhere('surname', 'LIKE', '%'.$this->searchTerm.'%')
                ->orWhere('email', 'LIKE', '%'.$this->searchTerm.'%')
                ->orderBy($this->sortField, $this->sortAsc)->paginate(8)
            ]);
        }
    }

How can I solve it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re mixing your and/or clauses. You want to make sure that user_id is always respected, but the rest are maybes. To fix that, pass the or clauses into a closure:

return view('livewire.dashboard.user-management', [
    'clients' => Client::where('user_id', '=', $user)
        ->where(function($query) {
            $query->where('name', 'LIKE', '%'.$this->searchTerm.'%')
                ->orWhere('surname', 'LIKE', '%'.$this->searchTerm.'%')
                ->orWhere('email', 'LIKE', '%'.$this->searchTerm.'%');
        })
        ->orderBy($this->sortField, $this->sortAsc)->paginate(8)
        
]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading