Laravel multiple filter with search - php

I want to search service providers and products, and filter by location and by service, or by location and by-products. i am using below code` $results = new ClientProfile;
if (request()->has('service-provider')) {
$results = $results->where('jobsc_id', request('service-provider'));
} elseif(request()->has('product')) {
$results = $results->where('product_id', request('product'));
} elseif(request()->has('city')){
$results = $results->where('divsec_id', request('city'));
} else {
$results = ClientProfile::searched();
}
$results = $results->where('profile_state', 'active')->paginate(10)->appends([
'service-provider' => request('service-provider'),
'product' => request('product'),
'city' => request('city'),
]);
return view('results')->with('results', $results);`
although it shows URL as domain.com/results?product=2&city=78 it shows all products without filter by city

You use if elseif therefore it when finding one, in the second also does not come.
use when instead if else
$results = new ClientProfile::when(request()->has('service-provider'), function($q){
$q->where('jobsc_id', request('service-provider'));
})
->when(request()->has('product'), function($q){
$q->where('product_id', request('product'));
})
->when(request()->has('city'), function($q){
$q->where('divsec_id', request('city'));
})
->when(count($request->all()) === 0, function($q){
$q->searched();
})
->where('profile_state', 'active')->paginate(10)->appends([
'service-provider' => request('service-provider'),
'product' => request('product'),
'city' => request('city'),
]);
return view('results')->with('results', $results);`

This code worked for me
$results = ClientProfile::when(request()->has('service-provider'), function($q){
$q->where('jobsc_id', request('service-provider'));
})->when(request()->has('product'), function($q){
$q->where('product_id', request('product'));
})->when(request()->has('city'), function($q){
$q->where('divsec_id', request('city'));
})->when(count(request()->all()) === 0, function($q){
$q->searched();
})->where('profile_state', 'active')->paginate(10)->appends([
'service-provider' => request('service-provider'),
'product' => request('product'),
'city' => request('city'),
]);

Related

Laravel 8: Convert array to same format of the model

In view, there's 2 tables and implemented the pagination for both but having a problem in the buttons
When we tried to change the page of table 1, the table 2 is also changed
In the controller, there's 4 model: 1) Purchase; 2) Direct Payments; 3) Sales; 4) Direct Collections.
purchases columns
id
number,
date_delivered
direct payments columns
id,
number
date
After getting the data from the perspective model we, rearrange the format
**Rearrange the format **
public function setToInputOutputTax($data,$module,$module_id)
{
$items = [];
foreach($data as $d => $datum) {
$items[] = [
'id' => $datum->id,
'checkbox' => 0,
// 'vat_type' => $vat_type,
'transaction_date' => isset($datum->date_delivered) ? $datum->date_delivered : $datum->date,
'transaction_number' => $module . $datum->number,
'module_id' => $module_id,
'vat_id' => $datum->vat->id,
'vat_code' => $datum->vat->code.' - '.$datum->vat->name,
'vat_rate' => $datum->vat_rate,
'net_of_vat' => $datum->net_of_vat,
'amount_due' => $datum->amount_due,
'balance' => $datum->vat_balance,
'amount_to_apply' => $datum->vat_balance,
];
}
return $items;
}
We merged the purchase & direct payments, same goes with sale & direct collection
$purchases = Purchase::select(
'id',
'number',
'date_delivered',
'vat_id',
'vat_rate',
'net_of_vat',
'amount_due',
'vat_balance'
)
->where('level_id',4)
->where('vat_balance','>', 0)
->where('company_id',Auth::user()->company_id)
->search(trim($this->input_search))
->orderBy('id', $this->order)
->get();
$purchases_input_tax = $this->setToInputOutputTax($purchases,'P-',201);
$direct_payments = DirectPayment::select(
'id',
'number',
'date',
'vat_id',
'vat_rate',
'net_of_vat',
'amount_due',
'vat_balance'
)
// ->union($purchases)
->where('level_id',4)
->where('vat_balance','>', 0)
->where('company_id',Auth::user()->company_id)
->search(trim($this->input_search))
->orderBy('id', $this->order)
->get();
// ->paginate(10, ['*'], 'input');
$direct_payments_input_tax = $this->setToInputOutputTax($direct_payments,'DP-',210);
$input_tax = array_merge($purchases_input_tax,$direct_payments_input_tax);
$col = collect($input_tax);
$input_currentPage = Paginator::resolveCurrentPage();
$currentPageItems = $col->slice(($input_currentPage - 1) * $this->input_size, $this->input_size)->all();
$all_input_taxes = new Paginator($currentPageItems, count($col), $this->input_size);
$sales = Sale::where('level_id',4)
->where('vat_balance','>', 0)
// ->where('status_id',[3,9])
->where('company_id',Auth::user()->company_id)
->search(trim($this->output_search))
->orderBy('id', $this->order)
->get();
// ->paginate(10, ['*'], 'output');
$sales_output_tax = $this->setToInputOutputTax($sales,'S-',101);
$direct_collections = DirectCollection::where('level_id',4)
->where('vat_balance','>', 0)
->where('company_id',Auth::user()->company_id)
->search(trim($this->output_search))
->orderBy('id', $this->order)
->get();
// ->paginate(10, ['*'], 'output');
$direct_collections_output_tax = $this->setToInputOutputTax($sales,'DC-',110);
$output_tax = array_merge($sales_output_tax,$direct_collections_output_tax);
$output_col = collect($output_tax);
$output_currentPage = Paginator::resolveCurrentPage();
$output_currentPageItems = $output_col->slice(($output_currentPage - 1) * $this->output_size, $this->output_size)->all();
$all_output_taxes = new Paginator($output_currentPageItems, count($output_col), $this->output_size);
Question: Is it possible to convert the array to same format of the model? Reason why we need to do this is because we need to paginate the new format

Laravel Eloquent get Clients which have active jobs

I'm working on a table which should show clients which have active jobs. I've got a page with all clients and this is working. I'm trying to get a query which is conditional on the client having active jobs. So here is what I have in my dataSource function:
public function dataSourcejobs(Request $request) {
$search = $request->query('search', array('value' => '', 'regex' => false));
$draw = $request->query('draw', 0);
$start = $request->query('start', 0);
$length = $request->query('length', 25);
$order = $request->query('order', array(0, 'desc'));
$filter = $search['value'];
$sortColumns = array(
0 => 'id',
1 => 'client',
2 => 'active_jobs',
3 => 'is_enabled',
4 => 'actions'
);
$query = Client::select( 'clients.*' );
if (!empty($filter)) {
$query->where( 'title', 'like', '%'.$filter.'%' );
}
$recordsTotal = $query->count();
$sortColumnName = $sortColumns[$order[0]['column']];
$query->orderBy($sortColumnName, $order[0]['dir'])
->take($length)
->skip($start);
$json = array(
'draw' => $draw,
'recordsTotal' => $recordsTotal,
'recordsFiltered' => $recordsTotal,
'data' => [],
);
$clients = $query->get();
foreach ($clients as $client) {
// Get active jobs for this client.
$jobs = Job::where( 'client_id', $client->id )->where('is_active', 1)->get();
$json['data'][] = [
$client->id,
$client->title,
'<button class="jobs">' . count($jobs) . ' Jobs</button>',
( $client->is_enabled === 1 ) ? 'Yes' : 'No',
'' . config( 'ecl.EDIT' ) . ' ' . config( 'ecl.WORK' ) . ''
];
}
return $json;
}
I've tried to do things like $query = Client::select( 'clients.*' )->count($client->jobs); but this is obviously wrong and errors. I also tried to do this in the loop (by checking the count) but this obvoiusly broke how the pagination works (but did show only clients with active jobs)
I should point out that the function above shown all clients even the ones which have no associated active jobs.
thanks
to get the count along with each client you can use withCount refer to this link https://laravel.com/docs/9.x/eloquent-relationships#counting-related-models
like the following
$query = Client::withCount('jobs');
as for getting the clients who only have jobs you can use whereHas

Laravel Eloquent use the orWhere query in my search system request

I tried to code a request with search system. Here the code:
$search = request()->get('search');
if(Auth::user()->hasRole('admin') || true)
{
list($orderBy, $orderDirection) = explode('.', request()->get('sort_by'));
$prestations = Prestation::with(
'service:id,name',
'facility:id,name'
)
->orWhere('service:name', 'regexp', "/$search/i")
->orderBy($orderBy, $orderDirection)
->simplePaginate(50);
$res = [
'results' => $prestations,
'total' => Prestation::all()->count(),
];
return $res;
}
The problem is that I don't know how to do something like I tried with the orWhere -> get all service name (from the relationship "with") which are equal to my $search.
Thank you.
Try this query.
$prestations = Prestation::with(
[
'service' => function($service) use($search){
$service->select(['id','name'])->where('name', $search);
},
'facility' => function($facility) {
$facility->select(['id','name'])
}
]
);

Eloquent calculate if I have more results left

I'm building a Products API. I need to return a collection of products and a variable telling me if I have more results starting from the last the answer has just returned me to show or hide a load more button. This is all I have until now:
$query = Product::query();
$query->where('category_id', $request->get('category_id'));
$query->orderBy('order', 'asc')
->orderBy('name', 'asc')
->skip($skip)
->take($take);
And this is how I return it:
return [
'products' => $query->get(['id', 'name', 'front_image', 'back_image', 'slug']),
'has_more' => ????
];
How can I calculate the has_more?
The easiest approach would be to query the database twice:
$query = Product::query()
->where('category_id', $request->get('category_id'))
->orderBy('order', 'asc')
->orderBy('name', 'asc');
$count = $query->count();
$hasMore = $skip + $take < $count;
$models = $query->skip($skip)
->take($take)
->get(['id', 'name', 'front_image', 'back_image', 'slug']);
return [
'products' => $models,
'has_more' => $hasMore
];
You can just get the count of the entire records and then simply do the check for has more like so:
<?php
$query = Product::query()
->where('category_id', $request->get('category_id'));
->orderBy('order', 'asc')
->orderBy('name', 'asc');
$count = $query->count();
return [
'products' => $query->skip($skip)
->take($take)
->get(['id', 'name', 'front_image', 'back_image', 'slug']),
'has_more' => ($hm = ($count - ($take + $skip))) > 0 ? $hm : false
];

Laravel 5.2 - Update previous query

I have this query:
Sendqueue::select()
->where('userID', Session::get('uid'))
->where('campaign', $id)
->where('status', 'pending')
->update(array(
'status' => 'stopped',
));
The problem is that the amount of records it has to go through to do the update causes it to take around 15 minutes or so to finish.
I would like to split it up so the select and update queries are separate entities. Something sort of like this:
$pending = Sendqueue::select()
->where('userID', Session::get('uid'))
->where('campaign', $id)
->where('status', 'pending')
->get();
$pending->update(array(
'status' => 'stopped',
));
How would I go about doing this? Or is there an easier way?
Thanks!
I wasn't thinking, I figured out the answer. I had to run the second part in a foreach like so:
$records = Sendqueue::select()
->where('userID', Session::get('uid'))
->where('campaign', $id)
->where('status', 'pending')
->get();
foreach ($records as $record) {
DB::table('sendqueue')
->where('ID', $record->ID)
->update(['status' => 'stopped']);
}
protected $table="user";
public function updateUser($id,$username)
{
$resultData = array();
$updateArray = array('user_name'=>$username);
$update=DB::table('user')
->where('user_id', $id)
->update($updateArray);
return $resultData['status'] = true;
}
$my_id = preg_replace ('#[^0-9]#', '', $request->id);
if (! empty ($my_id)) {
$this->c->where ('id', $my_id )->update ( [
'first_name' => $request->get ( 'first_name' ),
'last_name' => $request->get ( 'last_name' ) ,
'phone' => $request->get ( 'phone' )
] );`enter code here`
\Session::flash ('message', 'Update Successful');
return redirect ('customer');
}
$this->edit ();
http://developer.e-power.com.kh/update-query-in-laravel-5-2/

Categories