Php 我们可以根据请求在laravel中添加属性吗

Php 我们可以根据请求在laravel中添加属性吗,php,laravel,laravel-5.3,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,

我想在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\u格式逐个验证这些代码。问题是,如果用户根据选择的日期选择2月31日,您可以使用
merge
方法

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

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

$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)));
我的方式是:

$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
]);

希望这对某人有所帮助

我可以使用的另一个选项是单个输入,但3选择字段更方便用户
$request->合并(['birth'=>'Your Value'])然而,您在这里做了一些扩展,使用Laravel5.4,您可以将验证从控制器拆分为一个单独的文件。无论如何,要向
$request
中注入一个值,您可以使用
$request->merge()
方法。@white comet您可以使用一个日期选择器,它将完全绕过此方法issue@Mjh如果这是唯一的办法,我知道laracst有免费视频的形式要求感谢男子我会尝试it@adamj-不会的。即使你实现了一个日期选择器,你仍然可以发送你想要的任何东西到服务器。哦,我不需要使用表单请求,谢谢你@Patrick Reck和Mjh