2016-01-18 90 views
2

我的響應表中的我的group列的默認值爲「city」。我的代碼在下面進行查找,看看默認值是否應該在...或其他值中;默認值爲Laravel可選列

$group = Group::where('token', $request->input('groupToken'))->first(); 

$group = ($group ? $group->value : 'city'); 

$response = Response::create([ 
    'token' => $token, 
    'group' => $group, 
]); 

理想我想擺脫這種$group = ($group ? $group->value : 'city');線,只是在$group不傳遞給create()方法如果Group::where返回null。

這是如何完成的?

回答

2

試試這個:

$group = Group::where('token', $request->input('groupToken'))->first(); 

$data['token'] = $token; 

if($group != null){ 
    $data['group'] = $group->value; 
} 

$response = Response::create($data); 
當然
+0

。 '$ data'與一組數據。這是同一件事!我多麼愚蠢。謝謝 – mikelovelyuk

0

而不是->first()您可以使用firstOrFail()並將其包裝在try-catch,如果沒有返回,則會拋出ModelNotFoundException

喜歡的東西(未經測試):

$data['token'] = $token; 
try { 
    $group = Group::where('token', $request->input('groupToken'))->firstOrFail(); 
    $data['group'] = $group; 
} catch (ModelNotFoundException $ex) { 
    // Handle exception 
} 

$response = Response::create(
    $data 
);