Laravel Eloquent How to apply condition on "with" datas on the output? - php

here my code :
$prestations = Prestation::with(
[
'service' => function($service) use($searchService) {
$service->select(['id','name'])->where('name', 'regexp', "/$searchService/i");
},
'facility' => function($facility) use($searchPartenaire) {
$facility->select(['id','name'])->where('name', 'regexp', "/$searchPartenaire/i");
}
]
)
->where('name', 'regexp', "/$search/i")
->orderBy($orderBy, $orderDirection)
->simplePaginate(50);
$res = [
'results' => $prestations,
'total' => Prestation::all()->count(),
];
The problem is that in the output of all datas where "service" and "facility" names are not equal on the $searchService and $searchPartenaire the values are replaced by "null".
So i don't want to have values in the output where the search variables are not equals.
Thank you.

you can try like this
$prestations = Prestation::with('service','facility');
$prestations->whereHas('service', function ($query) use ($searchPartenaire) {
$query->Where('name', 'like', '%' . $searchPartenaire . '%');
});
$prestations->whereHas('facility', function ($query) use ($searchPartenaire) {
$query->Where('name', 'like', '%' . $searchPartenaire . '%');
});
$prestations->where('name', 'like', '%'.$search.'%')
->orderBy($orderBy, $orderDirection)
->simplePaginate(50);
return $res = [
'results' => $prestations,
'total' => Prestation::all()->count(),
];
1st create instances of Prestation $prestations = Prestation::with('service','facility')
then apply the condtion this is good approach in seach

Here my code after Kamlesh Paul suggestion :
$prestations = Prestation::with('service','facility');
$prestations->whereHas('service', function ($query) use ($searchService) {
$query->where('name', 'regexp', "/$searchService/i");
});
$prestations->whereHas('facility', function ($query) use ($searchPartenaire) {
$query->where('name', 'regexp', "/$searchPartenaire/i");
});
$prestations->where('name', 'regexp', "/$search/i")
->orderBy($orderBy, $orderDirection)
->simplePaginate(50);
$res = [
'results' => $prestations,
'total' => Prestation::all()->count(),
];
return $res;
But there is an infinite calls of http request, i think that the problem is when the where don't find an equal name, anyone have a suggest ?
Thank's.

I finnaly found a solution very similar :
$prestations = Prestation::with('service','facility')
->whereHas('service', function ($query) use ($searchService) {
$query->where('name', 'regexp', "/$searchService/i");
})
->whereHas('facility', function ($query) use ($searchPartenaire) {
$query->where('name', 'regexp', "/$searchPartenaire/i");
})
->where('name', 'regexp', "/$search/i")
->orderBy($orderBy, $orderDirection)
->simplePaginate(50);
$res = [
'results' => $prestations,
'total' => Prestation::all()->count(),
];
Thank's for your help.

Related

Laravel multiple filter with search

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

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

How to fix ''Property [id] does not exist in this statement"

I want to select from 2 table a data to all users and merge this data to object that I want to return
example
{
user:{
id:1,
name:bla,
saved cards:[
{id:1, name:test},
{id:2, name:test2}
]
},
{id:2, name:bla1,
saved cards:[
{id:1, name:test},
{id:2, name:test2},
{id:3, name:test3}
]
}
}
public function getalluser(Request $request)
{
$User_data = User::where('users.role', '=', 0)
->get();
$count = count($User_data);
for ($i = 0; $i < $count; $i++) {
$json_data[] = [
'user' => User::where('users.role', '=', 0)
->where( 'users.id', $User_data->id[$i])
->leftJoin('webrole', 'users.role', '=', 'webrole.id')
->get(),
'saved cards' => User::where('users.role', '=', 0)
->where( 'credit_cards.user_id', $User_data->id[$i])
->leftJoin('credit_cards', 'users.id', '=', 'credit_cards.user_id')
->get()
];
}
return response()->json($User_data);
}
foreach($User_data as $data) {
$json_data[] = [
'user' => User::where('users.role', '=', 0)
->where( 'users.id', $data->id)
->leftJoin('webrole', 'users.role', '=', 'webrole.id')
->get(),
'saved cards' => User::where('users.role', '=', 0)
->where( 'credit_cards.user_id', $data->id)
->leftJoin('credit_cards', 'users.id', '=', 'credit_cards.user_id')
->get()
];
}

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