I want to use single validate for birthday year, birth month, birth day as birthday for registration in laravel 5.4 here is my code
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');
}
nothing happen with that code, I can validate those 1 by 1 using date_format. the problem is what if the user select February and day is 31
According to the source, you can use the merge
method.
$request->merge(['birthday' => implode('-', [
$request->birth_year,
$request->birth_month,
$request->birth_date
])]);
There are many ways to do that. For example, you can use add()
method to add data to the Request
object:
$request->request->add(['birthday', implode('-', [
$request->birth_year,
$request->birth_month,
$request->birth_date
)]);
But here, I'd just do something like this:
$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)));
my way is:
$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
]);
Hope this helps someone