whereNotIn is not working or my code is wrong? - php

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

Related

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

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

Non functional laravel filter

I am trying to create an items filter based on user selections. The filter works with GET and fetches it's parameters from the url.
I tried using the laravel's when function but the filter is not working, it keeps returning the same result set without adhering to the filtration rule I wrote for it.
I am on Laravel 8 and I used the method outlined on Laravel's Conditional Clauses.
I feel like the problem is with the whereBetween clause between even after hard coding values into it, the result was the same as before.
Any help to fix this is greatly appreciated in advance.
$queryString = $request->query();
$sortBy = null;
$minMaxArray = array();
if($queryString){
if (array_key_exists('sortby', $queryString)) {
$sortBy = ($queryString['sortby'] == 'lowest') ? 'ASC' : 'DESC';
}
if (array_key_exists('min', $queryString) || array_key_exists('max', $queryString)) {
$minMaxArray['min'] = preg_replace("/,/", '', $queryString['min']) ?: 0;
$minMaxArray['max'] = preg_replace("/,/", '', $queryString['max']) ?: 1000000;
}
}
$tutors = DB::table('users')
->join('tutors', 'users.email', '=', 'tutors.tutorEmail')
->where([
['users.name', 'like', '%' . trim($searchText) . '%'],
['tutors.tutorStrength', '<>', '-'],
['users.status', 'active'],
['users.gender', '<>', '-'],
['users.phone', '<>', '-'],
['users.role', 'tutor']
])
->orWhere([
['tutors.tutorStrength', 'like', '%' . trim($searchText) . '%'],
['users.status', 'active'],
['users.gender', '<>', '-'],
['users.phone', '<>', '-'],
['users.role', 'tutor'],
])
->orWhere([
['users.location', 'like', '%' . trim($searchText) . '%'],
['tutors.tutorStrength', '<>', '-'],
['users.status', 'active'],
['users.gender', '<>', '-'],
['users.phone', '<>', '-'],
['users.role', 'tutor'],
])
->when($minMaxArray, function ($subQuery) use ($minMaxArray){
return $subQuery->whereBetween('tutors.tutorFee', $minMaxArray);
})
->when($sortBy, function ($subQuery) use ($sortBy){
return $subQuery->orderBy('tutors.tutorFee', $sortBy);
}, function ($subQuery){
return $subQuery->inRandomOrder();
})
->select('tutors.tutorFee', 'tutors.feeType', 'tutors.tutorOccupation', 'tutors.tutorStrength', 'users.*')->distinct()->paginate(20);
I fixed it. Turned out that I needed to duplicate the when conditional clauses on each where and orWhere clause.
I appreciate Kamlesh Paul for trying to help.

is there a way to use where like query in laravel with variable from GET method?

i want to filter with like in laravel project and paginate with laravel paginate, i try this code
$search = $request->get('query');
$products= DB::table('products')
->where('nama_produk', 'LIKE', '%'.$search.'%')
->paginate(6);
when use this code nothing error but it return all of data in my database table and not filtered.
if i use this code
$search = $request->get('query');
$products= DB::table('products')
->where('nama_produk', 'LIKE', '%test%')
->paginate(6);
it Worked :(
can someone help me to solve this problem ?
This is my search controller :
public function search(Request $request){
$query = $request->query;
$search = Post::where('post_title', 'LIKE', "%$query%")->orWhere('post_body', 'LIKE', "%$query%")->orWhere('post_tags', 'LIKE', "%$query%")->orderBy('created_at')->paginate(10);
return view('front.search', ['posts'=> $search, 'query'=> $query]);
}
Hope this helps.

Categories