在 Laravel 获取区域设置会话并相应地选择查询
getting Locale session on Laravel and selecting query accordingly
我正在尝试 select 一个 sql 查询,具体取决于为区域设置语言设置的会话。然而,尽管它应该很简单,但现在我在视图中得到一个 "invalid argument for the foreach array",也就是说,它没有传递参数。在添加检查区域设置之前,它确实 return 正确地用于英语,但是当我现在添加另一种语言时,IF 没有做出决定,因为检查会话不知何故没有正确编写或者我不知道是什么。我一直在谷歌搜索,它是这样读的:
if (\Session::get('locale') == 'en')
{
$listings = \DB::table('properties')
->join('english_descriptions', 'property_id', '=', 'properties.id' )
->select('endescription','properties.id','houses1','price', 'bedrooms', 'm2', 'entitle')
->get();
return $listings;
}
else{
if (\Session::get('locale') == 'es')
{
$listings = \DB::table('properties')
->join('spanish_descriptions', 'property_id', '=', 'properties.id' )
->select('esdescription','properties.id','houses1','price', 'bedrooms', 'm2', 'estitle')
->get();
return $listings;
}
我的控制器函数现在看起来像这样:
public function showListings()
{
var_dump(\Session::getLocale());
$listings = Property::returnListings();
return \View::make('listings', compact('listings'));
}
确保在使用 if-statements
时始终有后备 return 值。
$listings = []; // this will be the default return value if no condition is met
if (\Session::get('locale') == 'en') {
// query for listings in 'en'
}
else if (\Session::get('locale') == 'es') {
// query for listings in 'es'
}
return $listings;
现在对于语言环境会话,转储 \Session::get('locale')
的值以检查该值是否真的是 en
或 es
。
您可能希望使用 \App::getLocale();
而不是从会话中而是从应用程序本身检索区域设置值
我正在尝试 select 一个 sql 查询,具体取决于为区域设置语言设置的会话。然而,尽管它应该很简单,但现在我在视图中得到一个 "invalid argument for the foreach array",也就是说,它没有传递参数。在添加检查区域设置之前,它确实 return 正确地用于英语,但是当我现在添加另一种语言时,IF 没有做出决定,因为检查会话不知何故没有正确编写或者我不知道是什么。我一直在谷歌搜索,它是这样读的:
if (\Session::get('locale') == 'en')
{
$listings = \DB::table('properties')
->join('english_descriptions', 'property_id', '=', 'properties.id' )
->select('endescription','properties.id','houses1','price', 'bedrooms', 'm2', 'entitle')
->get();
return $listings;
}
else{
if (\Session::get('locale') == 'es')
{
$listings = \DB::table('properties')
->join('spanish_descriptions', 'property_id', '=', 'properties.id' )
->select('esdescription','properties.id','houses1','price', 'bedrooms', 'm2', 'estitle')
->get();
return $listings;
}
我的控制器函数现在看起来像这样:
public function showListings()
{
var_dump(\Session::getLocale());
$listings = Property::returnListings();
return \View::make('listings', compact('listings'));
}
确保在使用 if-statements
时始终有后备 return 值。
$listings = []; // this will be the default return value if no condition is met
if (\Session::get('locale') == 'en') {
// query for listings in 'en'
}
else if (\Session::get('locale') == 'es') {
// query for listings in 'es'
}
return $listings;
现在对于语言环境会话,转储 \Session::get('locale')
的值以检查该值是否真的是 en
或 es
。
您可能希望使用 \App::getLocale();