Reputation: 63
so I have a question. With laravel u can use the Eloquent library to create dynamic queries, but here's my problem. I have an external database which has stored procedures I need to call. I figured out that this code works.
$results = DB::connection('sqlsrv')->select($query);
But I need to know if there's a way to build the query dynamically cause not all the data in my form must be filled tho my stored procedure requires either some value or 'NULL' otherwise.
Here's what I have so far and it works, but it's not dynamic and I have to make a lot of junk make it so
$query = 'exec PROCEDURE_HERE "'.$request->name.'","'.$request->flastname.'","'.$request->mlastname.'",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0,null,"'.$request->datepicker.'",0,null';
And I have this function to handle the null values but the problem is since the query have " (those things) to build the query my final query looks like this
public function adaptRequest(Request $request){
if (!isset($request->name)){
$request->name = "null";
}
if (!isset($request->flastname)){
$request->flastname = "null";
}
if (!isset($request->mlastname)){
$request->mlastname = "null";
}
if ($request->datepicker == ""){
$request->datepicker = "null";
}
return $request;
}
exec PROCEDURE "null","null","null",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,0,null,"null",0,null
What I need to know is if there's a way to work this thing around like java does with Prepared statements where in the variables I place a '?' and then fill the data separately, kinda like this and then fill the '?'
$query = 'exec PROCEDURE_HERE ??,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?'
Any help would be awesome thanks
Upvotes: 0
Views: 1109
Reputation: 489
Use query in this form:
$query = User::select(...)->join(..);
if(condition){
$query->where(...);
}
if(condition){
$query->where(...);
}
$query->get(...);
Upvotes: 1