我的回复表中的group
列的默认值为" city"。我的下面的代码进行查找以查看默认值是否应该进入...或其他值;
$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');
返回null,我希望摆脱此$group
行并且不将create()
传递给Group::where
方法。
这是怎么做到的?
答案 0 :(得分:2)
试试这个:
$group = Group::where('token', $request->input('groupToken'))->first();
$data['token'] = $token;
if($group != null){
$data['group'] = $group->value;
}
$response = Response::create($data);
答案 1 :(得分: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
);