Home >Database >Mysql Tutorial >How to Bind Parameters in Laravel Raw Queries with a Model

How to Bind Parameters in Laravel Raw Queries with a Model

DDD
DDDOriginal
2024-11-15 01:31:02829browse

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);

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!

Statement:
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