Non functional laravel filter - php

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.

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

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

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.

Laravel Eloquent search two optional fields

I'm trying to search two optional tables using eloquent:
$users = User::where('ProfileType', '=', 2)
->where(function($query) {
$query->where('BandName', 'LIKE', "%$artist%");
$query->or_where('Genre', 'LIKE', "%$genre%");
})->get();
This works fine for return all results when a user does an empty search, but I am not sure how to adjust this for to search for bandname when that is present and vise versa.
Just to explain what happens on answer below:
Eloquent does a tricky thing here: When you call User::where(...) it returns a Database\ Query object. This is basically the same thing as DB::table('users')->where(...), a chainable object for constructing SQL queries.
So having:
// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
$query->where(function($query) {
// Adds a clause to the query
if ($artist = Input::get('artist')) {
$query->where_nested('BandName', 'LIKE', "%$artist%", 'OR');
}
// And another
if ($genre = Input::get('genre')) {
$query->where_nested('Genre', 'LIKE', "%$genre%", 'OR');
}
});
// Executes the query and fetches it's results
$users = $query->get();
Building on Vinicius' answer here's what worked:
// Instantiates a Query object
$query = User::where('ProfileType', '=', '2');
// Adds a clause to the query
if ($artist = Input::get('artist')) {
$query->where('BandName', 'LIKE', "%$artist%");
// Temp Usernamesearch
$query->or_where('NickName', 'LIKE', "%$artist%");
}
// Genre - switch function if artist is not empty
if ($genre = Input::get('genre')) {
$func = ($artist) ? 'or_where' : 'where';
$query->$func('Genre', 'LIKE', "%$genre%");
}
// Executes the query and fetches it's results
$users = $query->get();
Turns out that the second optional field must use or_where only if $artist is not set.
Thanks for your help
I think this is what youre after. Your view would have a form to search artist/genre one or the other can be set, or both, or none.
$users = User::where('ProfileType', '=', 2);
if (Input::has('artist')) {
$users = $users->where('BandName', 'LIKE', '%'.Input::get('artist').'%');
}
if (Input::has('genre')) {
$users = $users->where('Genre', 'LIKE', '%'.Input::get('genre').'%');
}
$users = $users->get();
$query = FormEntry::with('form')->where('domain_id', $id);
$query->where(function($query) use ($search, $start, $limit, $order, $dir) {
$query->where('first_name', 'LIKE', "%{$search}%")
->orWhere('last_name', 'LIKE', "%{$search}%")
->orWhere('email', 'LIKE', "%{$search}%")
->offset($start)
->limit($limit)
->orderBy($order, $dir);
});
$entries = $query->get();
$totalFiltered = $query->count();

Categories