Home > Database > Mysql Tutorial > body text

How to Bind Parameters in Laravel Raw Queries with a Model

DDD
Release: 2024-11-15 01:31:02
Original
741 people have browsed it

How to Bind Parameters in Laravel Raw Queries with a Model

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);
Copy after login

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]);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template