Ad

Laravel Optional Columns On Default Values

- 1 answer

My group column in my responses table has a default value of "city". My code below does a lookup to see if the default value should go in... or some other value;

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

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

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

Ideally I want to get rid of this $group = ($group ? $group->value : 'city'); line and just not pass in $group to the create() method if the Group::where returns null.

How is this done?

Ad

Answer

Try this:

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

$data['token'] = $token;

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

$response = Response::create($data);
Ad
source: stackoverflow.com
Ad