Problem with updating date from form to database - php

I am trying to update date_of birth column in database and when I submit my form I get this error
DateTime::__construct(): Failed to parse time string (25/03/1995) at position 0 (2): Unexpected character
Now in my blade I formated date of birth to show d/m/Y and when updating I think it updates Y/m/d, because when I remove format function from my blade it works fine. So I need help on how to update with format('d/m/Y') in my database and how to validate it properly in my form request validation. Any help is appreciated. Here is my code.
index.blade.php
<input type="text" placeholder="dd/mm/yyyy" name="date_of_birth" value="{{ $userForShowProfile->date_of_birth ? $userForShowProfile->date_of_birth->format('d/m/Y') : "" }}">
UserController.php
public function updateProfileCharacteristics(UpdateProfileCharacteristicsRequest $request)
{
$user = Auth::user();
$user->update(
[
'date_of_birth' => $request->date_of_birth,
'age' => Carbon::now()->diffInYears($request->date_of_birth),
'updated_at' => Carbon::now()
]
);
return redirect()->route('profile.show', [$user->username]);
}
UpdateProfileCharacteristicsRequest.php
public function rules()
{
return [
'date_of_birth' => ['date'],
];
}

Since you are sending the date in a custom format in the request, you will need to parse it to a format that matches the one in the database column before inserting it:
$user->update(
[
'date_of_birth' => Carbon::createFromFormat("d/m/Y", $request->date_of_birth)->format('Y-m-d'), // parse the right format here
'age' => Carbon::now()->diffInYears(Carbon::createFromFormat("d/m/Y", $request->date_of_birth)),
'updated_at' => Carbon::now()
]
);
And for that date format to pass validation you can use the date_format:format rule instead of date:
public function rules()
{
return [
'date_of_birth' => ['date_format:"d/m/Y"'],
];
}

What is the column type in you database migration? If it is check if it DATE or DATETIME or TIMESTAMP, It is supposed to be DATE hence you can format your date to be Y-m-d.

If you are to save a DATE to DB it should be in the format of Y-m-d.
so try this:
public function updateProfileCharacteristics(Request $request)
{
$user = Auth::user();
$user->update([
'date_of_birth' => Date('Y-m-d',strtotime($request->date_of_birth)),
'age' => Carbon::now()->diffInYears($request->date_of_birth),
'updated_at' => Carbon::now()
]);
return redirect()->route('profile.show', [$user->username]);
}

Related

How to use m/d/Y date format Laravel 5.6

I am using Laravel 5.6 and i need to add birthday with m/d/Y format but get date error. Example for this value '09-20-2018'.
The birthday is not a valid date.
public function rules()
{
return [
'birthday' => 'required|date|date_format:m-d-Y',
];
}
You should try this:
public function rules()
{
return [
'birthday' => 'date_format:m/d/Y|required|date',
];
}

How to bypass muliple validation attribute values inside validation messages in Laravel?

I've made a custom validator, that compares two dates, and I want to show a message to the user which says the one date (the invoicedate in my example) must be earlier than the other one (the deadline in my example).
Inside my custom validator I write:
public static validateInfo(Request $request)
{
$validator = Validator::make($request->all(), [
'referencenumber' => 'required|min:2|max:64',
'invoicedate' => 'required|date',
'deadline' => 'null|date'
]);
$validator->after(function ($validator) use ($request) { // custom static function where I compare two dates using strtotime(), if invoicedate and deadline are still valid, and return false or true
if (InvoiceValidator::invalidDeadline($validator, $request)) {
$validator->errors()->add('deadline', __('validation.negative_date_difference', [
'attribute1' => 'deadline',
'attribute2' => 'invoicedate'
]));
}
});
return $validator;
}
And inside resources\lang\en\validation.php I write:
<?php
return [
// ...
'negative_date_difference' => 'The :attribute1 may not be earlier than the :attribute2.',
// ...
'attributes' => [
'referencenumber' => 'Reference Number', // This works. It's fine
'invoicedate' => 'Invoice Date' // But this does not work, of course, because I wrote $validator->errors()->add('deadline'...); so the deadline is the only targetted attribute name here
],
]
Current output is:
The Deadline may not be earlier than the invoicedate.
My question: how to bypass invoicedate, when this is the message I want to see?
The Deadline may not be earlier than the Invoice Date.
Inside resources\lang\en\messages.php I've added a new message:
<?php
return [
'invoice_date' => 'Invoice Date'
]
Then edited my custom validation function, as follows:
if (InvoiceValidator::invalidDeadline($validator, $request)) {
$validator->errors()->add('deadline', __('validation.negative_date_difference', [
'attribute1' => 'deadline',
'attribute2' => __('messages.invoice_date') // This works
]));
}

Laravel date validation literal 'after' value

I have created a form request file which validates my start_date form input.
public function rules()
{
return [
'start_date' => 'required|date|after:2017-06-31',
];
}
I have placed a literal value in the after value, this however doesn't look like its working. Can someone advise the best way to do this?
Edit:
This is the dump from my $request->all();
{
"_token": "tZa4e39ejrGHtrlpOYrUPfZ8PgSeD8FelY4voKni",
"start_date": "2017-07-01"
}
This is my form request validation:
public function rules()
{
return [
'start_date' => 'required|date_format:Y-m-d|after:2017-06-31',
];
}
I am using Laravel v5.4
The dates will be passed into the PHP strtotime function so change
your date format to Y-m-d .
public function rules()
{
return [
'start_date' => 'required|date|date_format:Y-m-d|after:2017-06-31',
];
}

can we add properties on request in laravel

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

Laravel 5.2 validation: date_format:Y.m.d not working

I try to validate a POST request.
The format is: d.m.Y (12.1.2017)
My rule is required|date_format:d.m.Y for this field.
I get this error message:
InvalidArgumentException in Carbon.php line 425:
Unexpected data found.
Unexpected data found.
Data missing
If I change the . to - or even / it is working -> POST data changed before to match the rule.
I need the German format for this.
edit:
My validation rules:
public function rules()
{
return [
'title' => 'required|max:255',
'expiration_date' => 'required|date_format:d.m.Y',
//'description' => 'required',
'provision_agent' => 'required|integer|between:0,100',
'discount_consumer' => 'required|integer|between:0,100',
'quota' => 'required|integer',
];
}
Wrap your Format should work i just tried with 5.2 it's working fine.
public function rules()
{
return [
'title' => 'required|max:255',
'expiration_date' => 'required|date_format:"d.m.Y"',
//'description' => 'required',
'provision_agent' => 'required|integer|between:0,100',
'discount_consumer' => 'required|integer|between:0,100',
'quota' => 'required|integer',
];
}
But the error what you added in question InvalidArgumentException in Carbon.php line 425: it seems something else my guess you are using expiration_date some where in controller or model like this with Carbon
echo Carbon::createFromFormat('Y-m-d', '12.1.2017');
You should try something like this
echo Carbon::parse('12.1.2017')->format('Y-m-d')
Wrap your format into quotes:
'date_format:"d.m.Y"'
Try like this,
public function rules()
{
return [
'title' => 'required|max:255',
'expiration_date' => 'date_format:"d.m.Y"|required', // I have changed order of validation
//'description' => 'required',
'provision_agent' => 'required|integer|between:0,100',
'discount_consumer' => 'required|integer|between:0,100',
'quota' => 'required|integer',
];
}
Hope this will solve your problem.
If you don't succeed solving the issue otherwise, you can still use a custom validation rule:
Validator::extend('date_dmY', function ($attribute, $value) {
$format = 'd.m.Y';
$date = DateTime::createFromFormat($format, $value);
return $date && $date->format($format) === $value;
}, 'optional error message');
The extra check $date->format($format) === $value is to avoid erroneously accepting out-of-range dates, e.g. "32.01.2017". See this comment on php.net.
Once the custom validation rule has been defined, you can use it like so:
public function rules() {
return [
'expiration_date' => 'required|date_dmY',
];
}

Categories