You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中使用带查询参数的URL请求API返回空数组如何解决?

问题原因

  • 路由参数类型和请求传参方式不匹配:你当前路由定义的是路径参数,要求参数拼接在URL路径中,但实际请求是将参数放在查询字符串(?后部分)传递,路由无法匹配参数,导致控制器拿到的参数为空,查询无结果。
  • Eloquent查询构造器多条件写法不规范:where('name', $name,'surname',$surname)不符合Laravel查询构造器的语法要求,无法正确拼接查询条件。

解决方案

方案1:保留路径参数定义,调整请求方式

  1. 将请求URL改为路径传参格式:
http://localhost/project-test/public/api/contactos/buscar/eric/almendras
  1. 修正控制器的查询写法:
public function buscar($name,$surname){
    // 两种合法的多条件where写法二选一即可
    $contacto = Contacto::where('name', $name)->where('surname', $surname)->get();
    // 或者传二维数组:Contacto::where([['name',$name],['surname',$surname]])->get();
    return $contacto;
}

方案2:保留现有查询参数请求方式,调整路由和控制器

  1. 修改api.php中的路由定义,去掉路径参数声明:
Route::get('contactos/buscar','ContactosController@buscar');
  1. 修改控制器逻辑,从请求实例中获取查询参数:
// 控制器头部先引入Request类
use Illuminate\Http\Request;

public function buscar(Request $request){
    $name = $request->input('name');
    $surname = $request->input('surname');
    $contacto = Contacto::where('name', $name)->where('surname', $surname)->get();
    return $contacto;
}

内容的提问来源于stack exchange,提问作者Eric Efrain Almendras Arnez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:06:03