save where clause in a variable and use it in laravel query - laravel

I have saved all of my where clause in a variable and i'm trying to join that variable inside laravel query but its not working. Here is mine code
$where .= "";
$where .= '->where("product_details.title", '.$request->title.')';
$where .= '->where("product_details.id", '.$request->id.')';
$results = DB::table('product_details').'$where'.->get();
How to use variable inside query?

you can used like that by using if condition statement for dynamic query
$results = DB::table('product_details')
if($request->title) {
$results->where("product_details.title", $request->title);
}
if($request->id) {
$results->where("product_details.id", $request->id);
}
$result->get();

I am not sure why you want to do this. The following should just work.
DB::table('product_details')
->where([
'product_details.title' => $request->title
'product_details.id' => $request->id
])
->get();
Now, let's say that you may not always have a title or id from the request, you could also do this
DB::table('product_details')
->when($request->title, function ($query, $title) {
return $query->where('product_details.title', $title);
})
->when($request->id, function ($query, $id) {
return $query->where('product_details.id', $id);
})
->get();

this will not work because you are saving text in string and output will be on string you need to convert it to eval Try This.
$results = DB::table('product_details') . eval ($where) .->get();

Related

I am running a eloquent query, but i am stuck in a position

I am new in Laravel.
$year 'all' is every possible year
all, 2022, 2021, 2020, 2019
if i pass params any of them except all its working fine.
but when i pass all as condition. i have no idea what to do?
Please help me.
public function findResultServiceFeeDubai($address, $type, $year, $norows){
$result = DB::table('service-charges')
->select('address', 'year', 'type', 'total_charge_sqft')
->orWhere('address', 'LIKE', "%".$address."%")
->where('type', $type)
->where('year', $year)
->limit($norows)
->get();
$response = $result;
return response()->json($response, 200);
}
Route::get('/findResultServiceFeeDubai/{name}/{type}/{year}/{norows}',[UserController::class,'findResultServiceFeeDubai'])->name('findResultServiceFeeDubai');
You are calling methods on a Query Builder. It is an object so you can assign it to a variable and make calls to it as needed to build your query. The get call is what is actually executing the query and returning a result. If you want to conditionally add query conditions to that query you can just use if statements (if you prefer to not use the functional approach):
$query = DB::table('service-charges')
->select('address', 'year', 'type', 'total_charge_sqft')
->where('address', 'LIKE', '%'. $address .'%')
->limit($norows);
if ($year !== 'all') {
$query->where('year', $year);
}
if ($type !== 'all') {
$query->where('type', $type);
}
$result = $query->get();

Laravel OrWhere having two conditions is not so obvious

Why in Eloquent a simple query as this one is not working?
$matches = DB::table("matches")
->where(["team_a"=> $request->tid, "match_tipo"=>3])
->orWhere(["team_a"=> $request->tid, "match_tipo"=>3])
->first();
According to with other examples here on Stackoverflow, I should use a query in Where like:
$matches = DB::table("matches")
->where(["match_tipo"=>3])
->where(function($query, $request) {
$query->where('team_h',$request->tid)
->orWhere('team_a',$request->tid);
})
->first();
But I should pass a second parameter ($request).
How is the simplest way to do this query?
You can make this as like this.
->where(["match_tipo"=>3]) this will be ->where("match_tipo",3) and use($tid) after query.
$tid = $request->tid;
$matches = DB::table("matches")
->where("match_tipo",3)
->where(function($query) use($tid) {
$query->where('team_h',$tid)
->orWhere('team_a',$tid);
})
->get();
while using the Callback or Closure as the where function Parameter you will only the one argument which is Current Object
Methods Can used to Pass the $request
Method One
$matches = DB::table("matches")
->where(["match_tipo"=>3])
->where(function($query) use ($request) {
$query->where('team_h',$request->tid)
->orWhere('team_a',$request->tid);
})
->first();
Method Two
$matches = DB::table("matches")
->where('match_tipo','=',3)
->when($request->tid,function($query) use ($request) {
return $query->where('team_h',$request->tid)
->orWhere('team_a',$request->tid);
})
->first();
Try this query :
$matches = DB::table("matches")
->where('match_tipo',3)
->whereRaw('team_a = "'.$request->tid.'" OR team_h = "'.$request->tid.'"')
->first();

Laravel eloquent using loop

I am using eloquent query to filter data. My query is like this and it is working perfectly for now.
$users = User::where('username','LIKE','%'.request('username').'%')
->where('first_name','LIKE','%'.request('first_name').'%')
->where('last_name','LIKE','%'.request('last_name').'%')
->where('gender','LIKE','%'.request('gender').'%')
->where('password','LIKE','%'.request('password').'%')
->SimplePaginate(15);
My request data was like this.
However I need to update this query for dynamic fields. There can be different fields. What I did was to send the request in an associative array. So, my request data turned into like this,
What I intend to do is to put all request data in a search array. Then use a loop to run like the above query. How can I do that?
P.S. I checked in the forum and found some similar questions. Some of them are outdated. Others didn't solve my problem.
If I understand you right you can do like this:
$search = request('search', []);
$users = User::query();
foreach($search as $field=>$value)
{
$users = $users->where($field,'LIKE','%'.$value.'%');
}
$users = $users->SimplePaginate(15);
You can try this.
$search = $request->get('search');
User::where(function ($q) use ($search){
foreach ($search as $key=>$value) {
if($value != null ){
$q->where($key, 'like', "%{$value}%");
}
}
})->get();
The where() clause can also accept an array. With that in mind, you could map over your search parameters and convert it to the format you want and then feed it into the query.
For example:
$search = [
'first_name' => 'John',
'last_name' => 'Smith'
];
$filters = collect($search)->map(function($value, $key) {
return [$key, 'LIKE', "%{$value}%"];
})->values()->toArray();
return User::where($filters)->SimplePaginate(15);

Parameters Group on eloquent query

I have little problem with my search query at the moment. When i run a search query with only the parameter "comite_id" it's working but when i want to run the search query with "comite_id" and the whereBetween with "date_min" and "date_max" the result is not right , it's seems the result don't care about the whereBetween clause because i don't get the right date range.
Someone knows where i'm doing wrong? thanks a lot in advance
Here my controller :
public function getRetrocession(Request $request){
$comites = Structure::where('type_structure_id' , '=' ,'3')->pluck('nom_structure' , 'id');
$search = $request->input('comite_id');
$dt_min = $request->input('dt_min');
$dt_max = $request->input('dt_max');
if ($search) {
$query = Retrocession::where('comite_id', '=', $search)
->orWhere(function ($q) use($search , $dt_min , $dt_max) {
$q->where('comite_id', '=', $search)
->whereBetween('dt_retrocession', [ $dt_min , $dt_max]);
});
}else {
$query = Retrocession::select();
}
$retrocessions = $query->orderBy('dt_retrocession', 'DESC')->paginate(10)
->appends(['recherche' => $search]);
return view('retrocession/index' , compact('retrocessions' , 'comites'));
}
Because you are using orWhere() it always call both where() and orWhere(); thus including the result of where() and orWhere(). You can try this way
$query = Retrocession::where('comite_id', $search)
->when($dt_min && $dt_max, function($q) use ($dt_min, $dt_max) {
$q->whereBetween('dt_retrocession', [$dt_min, $dt_max]);
});
So you always run the first where, and only include whereBetween() WHEN $dt_min and $dt_max are both true.
Bonne chance Mathieu.

Laravel 4 - Eloquent 'where' only if exists

I'm working in a search engine, and I have something like this in my Controller:
$user = User::where('description', 'LIKE', '%'.$keyword.'%')
->where('position', $position)
->where('age', $age)
->orderBy('created_at', 'DES')
->paginate(10);
What I want is to use the $position and $age filters only if they exist. I mean, if I only set the keyword, I expect the application to show me all the users with this keyword (whatever its position and age are).
I know a way to do it... using if($position == '')... else..., but I would like to do (if possible) in my Eloquent consult. Something like... ->where('position' ? $position).
Any idea how to do it in the simplest way?
Thanks in advance!
Using if conditions would be the best way to do this. As far as I know the functionality your after isn't built into Eloquent.
I would do it using conditionals like so:
$query = User::where('description', 'LIKE', '%'.$keyword.'%');
if($position) {
$query->where('position', $position);
}
if($age) {
$query->where('age', $age);
}
$user = $query->orderBy('created_at', 'DES')->paginate(10);
If you want to keep your controller clean and avoid if - else you can create some scopes in your model.
For exemple :
public function scopePosition($query, $position)
{
//If $position in empty, return the query without where clause
return !($position == '') ? $query->where('position', $position) : $query;
}
And :
public function scopeAge($query, $age)
{
//If $age in empty, return the query without where clause
return !($age== '') ? $query->where('age', $age) : $query;
}
And then use it like this:
$user = User::where('description', 'LIKE', '%'.$keyword.'%')
->position($position)
->age($age)
->orderBy('created_at', 'DES')
->paginate(10);
More abour query scope:
http://laravel.com/docs/eloquent#query-scopes

Resources