我们可以在laravel中根据要求添加属性

时间:2017-04-11 11:40:50

标签: php laravel laravel-5.3

我想使用单一验证作为生日年份,出生月份,出生日作为laravel 5.4注册的生日。这里是我的代码

public function register(Request $request)
{
    // here i want to add bithday input on reqeust but nothing happen
    $request->birthday = implode('-', array(
            $request->birth_year,
            $request->birth_month,
            $request->birth_date
        ));

    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    return redirect()->back()->with('info', 'User successfully registered');
}

该代码没有任何反应,我可以使用date_format验证这些1。问题是如果用户选择二月和一天是31

3 个答案:

答案 0 :(得分:2)

根据source,您可以使用merge方法。

$request->merge(['birthday' => implode('-', [
    $request->birth_year,
    $request->birth_month,
    $request->birth_date
])]);

答案 1 :(得分:1)

有很多方法可以做到这一点。例如,您可以使用add()方法将数据添加到Request对象:

$request->request->add(['birthday', implode('-', [
        $request->birth_year,
        $request->birth_month,
        $request->birth_date
    )]);

但是在这里,我会做这样的事情:

$data = $request->all();

$data['birthday'] = implode('-', [
        $request->birth_year,
        $request->birth_month,
        $request->birth_date
    ]);

$this->validator($data)->validate();

event(new Registered($user = $this->create($data)));

答案 2 :(得分:0)

我的方式是:

$all = $request->all();
$year = $all['birth_year'];
$month = $all['birth_month'];
$day = $all['birth_date'];

 // Create Carbon date
$date = Carbon::createFromFormat('Y-m-d', $year.'-'.$month.'-'.$day);
// $date = Carbon::createFromFormat('Y-m-d', $request->birth_year.'-'.$request->birth_month.'-'.$request->birth_date); another way

//add new [birthday] input
$request->request->add(['birthday' => $date->format('Y-m-d')]); 

$validatedData = $request->validate([
    'first_name' => 'required|string|max:255',
    'last_name' => 'required|string|max:255',
    'email'    => 'required|string|email|max:255',
    'password' => 'required|string',
    'birthday' => 'required|date_format:Y-m-d|before:today',// validate birth day
]);

希望这对某人有帮助