Binding Parameters in Laravel Raw Queries with a Model
In Laravel, binding parameters to raw DB queries used on models can be tricky. However, here's a workaround that can help:
Problem:
The following query fails with an "Invalid parameter number" error due to mixed named and positional parameters:
$query = DB::raw("... :lat, :lng, (calc) AS ...")->having("calc", "<", :radius);
Solution:
Utilize the setBindings() method to set the query bindings manually, overriding the mixed parameters issue:
$query = DB::raw("... ?, ?, (calc) AS ...")->having("calc", "<", "?"); $query->setBindings([$lat, $lng, $radius]);
Explanation:
The DB::raw() statement uses question marks as positional parameters, allowing you to set them using setBindings() instead of named bindings. This approach allows you to employ the query builder's fluent interface without worrying about parameter mixing.
The above is the detailed content of How to Bind Parameters in Laravel Raw Queries with a Model. For more information, please follow other related articles on the PHP Chinese website!