【问题标题】:Function returns Null :: laravel函数返回 Null :: laravel
【发布时间】:2014-09-20 07:25:15
【问题描述】:

我有一个从数据库中获取值并返回的函数。当我回显时,该值确实存在。但返回值为null;

public static function getCountryCode($country) {       
    $country = (int) $country;      
    $x = Country::where('id', $country)->get();
    $country_code = '';         
    foreach($x as $row)             
        $country_code = $row->alpha_2;
    //return 'bd';      
    echo $country_code;         
    return $country_code; 
}

不知道那里出了什么问题。这是一个 laravel 项目。

调用此方法的函数

public function countryselect()
{
    $country_id = HomeController::detectCountry();
    $country_code = SiteController::getCountryCode($country_id);
    var_dump($country_code);
    return View::make('Layout.countryselect', compact('country_id', 'country_code'));
}

【问题讨论】:

  • 你能显示调用这个方法的代码吗?
  • public function countryselect() { $country_id = HomeController::detectCountry(); $country_code = SiteController::getCountryCode($country_id); var_dump($country_code); return View::make('Layout.countryselect', compact('country_id', 'country_code')); }
  • 如果将其添加到问题中会更容易格式化。那里有一个待定的编辑,但也需要引入。
  • 这是用来调用@bcmcfc的函数

标签: php function laravel-4 null


【解决方案1】:

您不必使用“foreach”功能。您可以更轻松地获取国家/地区代码。只需在 getCountryCode() 中进行一些更改,例如

public static function getCountryCode($countryId) {
    $countryId = (int) $countryId;      
    $country = Country::where('id', $countryId)->get()->first();
    return $country->code;
}

这将返回指定国家 ID 的国家代码。对变量使用描述性名称,就像您用于函数一样

【讨论】:

  • 谢谢让我知道这一点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-05
  • 2019-04-17
  • 1970-01-01
  • 2023-03-28
  • 2022-06-12
  • 2021-03-31
相关资源
最近更新 更多