首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何设置laravel可空函数参数

如何设置laravel可空函数参数
EN

Stack Overflow用户
提问于 2021-09-03 04:06:12
回答 3查看 37关注 0票数 1

我正在从事laravel电子商务项目,在功能中,我需要发送我需要发送的产品的品牌参数,如果我没有发送任何参数,它返回所有的产品

函数

代码语言:javascript
运行
复制
public function index($brand)
{
    if ($brand) {
        $products = Product::where('brand_id', '=', $brand)->get();

        return response()->json($products);
    } else {
        $products = Product::get();

        return response()->json($products);
    }
}

路线

代码语言:javascript
运行
复制
Route::get('/products/{brand}', 'App\Http\Controllers\ApiProductController@index');

当我在postman中尝试URL并写下特定品牌时,它成功地返回了产品,但当我没有成功时,它没有返回任何东西,而是返回了所有产品

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-09-03 04:20:34

您可以简单地将参数声明为null。因此,当你要传递参数时,它将获得传递的值,否则将为null。

代码语言:javascript
运行
复制
public function index($brand = null)
{
    if ($brand) {
        $products = Product::where('brand_id', '=', $brand)->get();

        return response()->json($products);
    } else {
        $products = Product::get();

        return response()->json($products);
    }
}

然后在路径定义中也将该参数设为可选

代码语言:javascript
运行
复制
Route::get('/products/{brand?}', 'App\Http\Controllers\ApiProductController@index');

现在,这应该如您所期望的那样工作。

票数 0
EN

Stack Overflow用户

发布于 2021-09-03 04:10:59

因为您已默认使用参数!..

代码语言:javascript
运行
复制
Route::get('/products/{brand?}', 'App\Http\Controllers\ApiProductController@index');

添加'?‘帮助laravel理解它

票数 0
EN

Stack Overflow用户

发布于 2021-09-03 04:46:52

你可以试试这样的东西,

代码语言:javascript
运行
复制
public function index($brand = null)
{
    $products = Product::when($brand, function ($query, $brand) {
        return $query->where('brand_id', $brand);
    })
    ->get();
    
    return response()->json($products);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69039374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档