How to search clients of the authenticated user? - php

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?

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)
]);

Related

Issue with implementing a search functionality with Laravel

I am trying to implement a search feature in a site. A user can specify a search string that could match a product_id, product_name or the product_sku. What I want to implement is a search function that would return all that matches.
What I've come with so far:
return Product::with(['getProductItem' => fn ($query) => $query->orWhere('itemSkuNumber', '=', $request->search)])
->where(
'name',
$request->has('match') ? '=' : 'like',
$request->has('match') ? $request->search : '%' . $request->search . '%'
)
->orWhere('id', '=', $request->search)->get();
This has worked if I specify a product_id or product_name but does not return anything if I provide an sku.
You should wrap orWheres with another where because it will try to filter all of them.
Product::with(['getProductItem'])
->whereHas('getProductItem', function ($query) use ($request) {
$query->where(function ($subquery) use ($request) {
$subquery->where('itemSkuNumber', '=', $request->search);
//put your orwhere queries in here
});
})
->get();
Try whereHas
$products = Product::query()
->with(['getProductItem'])
->whereHas('getProductItem', fn ($query) => $query->where('itemSkuNumber', '=', $request->search)]))
->orWhere(
'name',
$request->has('match') ? '=' : 'like',
$request->has('match') ? $request->search : '%' . $request->search . '%'
)
->orWhere('id', '=', $request->search)
->get();
#gguney, #Sumit,
Thanks for your help, :).
Got it working with:
return Product::with(['getProductItem'])
->whereHas('getProductItem', function ($query) use ($request) {
$query->where('itemSkuNumber', '=', $request->search);
})
->orWhere(
'name',
$request->has('match') ? '=' : 'like',
$request->has('match') ? $request->search : '%' . $request->search . '%'
)
->orWhere('id', '=', $request->search)
->get();
#Sumit,
You have extra parentheses and brackets.

how to use Laravel 8 query builder like eloquent for searching

I'm developing a simple CRM with Laravel 8 that needs to search in query string.
My query string would be look like:
http://127.0.0.1:8000/admin/users/supervisor?q=john&gender=m
Now the problem is how can I search in controller?
I want to do like this:
public function index (Request $request)
{
$role = getRoleCode($request->role);
$roles = Role::where('role', '=', $role);
if ($request->q) {
$roles->where('name', 'like', "%$request->$q%");
}
if ($request->gender) {
$roles->where('gender', '=', $request->gender);
}
$role->orderBy('id', 'desc')->paginate(20);
return view('admin.users.index', [
'roles' => $roles,
'role_name' => config('settings.roles')[$role],
'role_en_name' => $request->role,
'q' => $request->q,
'gender' => $request->gender
]);
}
I wonder why its not working and what is the standard way to do this.
I've tried:
Role::query();
but that didn't work either.
I've also tried:
$roles = Role::where('role', '=', $role)
->where('name', 'like', "%$request->$q%")
->where('gender', '=', $request->gender)
->orderBy('id', 'desc')
->paginate(20);
This codes works perfectly but we may not be sending the "q" or "gender" URL params.
PS: Sorry for my bad English :)
If you want to conditionally add where statements to your query you can use the if statements like you are attempting to do or use the when method of the Eloquent/Query Builder:
$roles = Role::where('role', $role)
->when($request->input('q'), fn ($query, $search) => $query->where('name', 'like', '%'. $search .'%'))
->when($request->input('gender'), fn ($query, $gender) => $query->where('gender', $gender))
->orderBy('id', 'DESC')
->paginate(20);
Laravel 8.x Docs - Queries - Conditional Clauses when
work with when() it's better
->when(true, function($query){$query->where('x', x);})

trying to search in a table or in its relation in laravel

I need to search for the code in the appointment table OR the patient name which is the appointment's relation. here is the code I reached so far but it is not working:
$lab = Lab::with(['patient' => function ($q) use ($search_query) {
$q->select('id', 'avatar', DB::raw('CONCAT(first_Name, " ", second_Name) AS name')
->where('name', 'like', "%{$search_query}%")
->orWhereRaw("concat(first_name, ' ', second_name) like '%$search_query%' ")
);
}])
->select('id', 'code')
->Where('code', 'like', "%{$search_query}%")
->limit(5)
->get();
Loding relation is different from applying 'where' on it, you sould load the relation and apply 'whereHas' in another statement:
$lab = Lab::with(['patient' => function ($q) {
$q->select('id', 'avatar', DB::raw('CONCAT(first_Name, " ", second_Name) AS name')
);
}])
->select('id', 'code')
->Where('code', 'like', "%{$search_query}%")
->orWhereHas('patient',function ($query) use ($search_query) {
$query->where('name', 'like', "%{$search_query}%");
})
->limit(5)
->get();

whereNotIn is not working or my code is wrong?

Currently, I'm adding items into a price list, however it should not let add the same item twice, or specifically the same ID. Articulo model has the ID that listas_precios_articulos model has as articulo_id.
I used whereNotIn clause to achieve that but it is not working. Can anyone tell me what is wrong with my code? Thanks!
public function findArticulo(Request $request)
{
$id = $request->id;
$articulos = Articulo::query()->select([
'id',
'codigo_interno',
'codigo_comercial',
'impuestos_venta',
'impuestos_compra',
'nombre',
'descripcion',
'status'])
->where('status','activo')->whereNotIn('id', function($query)use($id){
$query->select('articulo_id')
->from('listas_precios_articulos')
->where('lista_precio_id', $id)
->whereNotIn('estatus', ['eliminado']);
})
->where('nombre', 'like', "%".$request->nombre."%")
->Orwhere('codigo_interno', 'like', "%".$request->nombre."%")
->Orwhere('codigo_comercial' , 'like' , "%".$request->nombre."%")
->get()
->toArray();
return response()->json($articulos,200);
}
this query must return an array to make it correct in whereNotIn statement
$query->select('articulo_id')
->from('listas_precios_articulos')
->where('lista_precio_id', $id)
->whereNotIn('estatus', ['eliminado'])
->toArray();
and maybe this was a typo error ->Orwhere...must be ->orWhere
UPDATED
could you split the query and do this:
$id = $request->id;
$pluckedIds = ListasPreciosArticulo::
where('lista_precio_id', $id)
->where('estatus','!=','eliminado')
->pluck('id');
$articulos = Articulo::query()->select([
'id',
'codigo_interno',
'codigo_comercial',
'impuestos_venta',
'impuestos_compra',
'nombre',
'descripcion',
'status'])
->where('status','activo')->whereNotIn('id', [$pluckedIds])
->where('nombre', 'like', "%".$request->nombre."%")
->orWhere('codigo_interno', 'like', "%".$request->nombre."%")
->orWhere('codigo_comercial' , 'like' , "%".$request->nombre."%")
->get();
return response()->json($articulos,200);

How use orWhere in laravel elequent properly?

I want do following query in laravel elequent
select from table where cond1 and(cond or cond or cond..)and cond3.
I have used following code,
$invoice = Invoice::with("items", "salesPerson", "client");
if ($q = Request::input("q")) {
$invoice->where("invoices.invoice_number", 'LIKE', "%$q%");
$invoice->orWhere("invoices.reference_number", 'LIKE', "%$q%");
$invoice->orWhere("invoices.client_name", 'LIKE', "%$q%");
$invoice->orWhere("invoices.invoice_date", 'LIKE', "$q%");
$invoice->orWhere("invoices.due_date", 'LIKE', "$q%");
}
$invoice->whereNull("invoices.deleted_at");
but it return deleted records as well.How can I fix this?
In this case a nested where comes in handy:
$invoice = Invoice::with("items", "salesPerson", "client");
if ($q = Request::input("q")) {
$invoice->where(function($query) use ($q){
$query->where("invoices.invoice_number", 'LIKE', "%$q%");
$query->orWhere("invoices.reference_number", 'LIKE', "%$q%");
$query->orWhere("invoices.client_name", 'LIKE', "%$q%");
$query->orWhere("invoices.invoice_date", 'LIKE', "$q%");
$query->orWhere("invoices.due_date", 'LIKE', "$q%");
});
}
$invoice->whereNull("invoices.deleted_at");

Categories