Laravel可选列的默认值

时间:2016-01-18 12:45:32

标签: php oop laravel laravel-5

我的回复表中的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方法。

这是怎么做到的?

2 个答案:

答案 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
);