我在控制器方法中有一些示例代码,用于查找cookie并操作模型(如果存在),或创建新模型并返回新的cookie(如果它没有。
是否可以在返回视图之前添加Cookie,以便重复的代码只能写入一次?
我只是在寻找效率和整洁。
$cat = Cat::find($request->cookie('cat_id'));
if (null !== $cat) {
if ($cat->name === 'Felix') {
$cat->age = 10;
} else {
$cat->age = 8;
}
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
return redirect('/');
} else {
$cat = new Cat;
$cat->name = 'Ralf';
$cat->age = 12;
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
return redirect('/')->withCookie(cookie('cat_id', $cat->id,10000));
}
答案 0 :(得分:0)
当一个字符串传递给它时,redirect()
方法返回Illuminate\Http\RedirectResponse
,Laravel路由栈将其解释为发送特定响应头的方向。所以不要回两次,你可以这样做:
$cat = Cat::find($request->cookie('cat_id'));
$redirect = redirect('/');
if (null !== $cat) {
if ($cat->name === 'Felix') {
$cat->age = 10;
} else {
$cat->age = 8;
}
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
} else {
$cat = new Cat;
$cat->name = 'Ralf';
$cat->age = 12;
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
$redirect->withCookie(cookie('cat_id', $cat->id,10000));
}
return $redirect;