A four digit year could not be found Data missing - php

I'm trying to seed using factories in Laravel 5.2
My code dies in the User factory:
$factory->define(App\User::class, function (Faker\Generator $faker) {
$countries = Countries::all()->pluck('id')->toArray();
return [
'name' => $faker->name,
'email' => $faker->email,
'password' => bcrypt(str_random(10)),
'grade_id' => $faker->numberBetween(1, 5),
'country_id' => $faker->randomElement($countries),
'city' => $faker->city,
'latitude' => $faker->latitude,
'longitude' => $faker->longitude,
'role_id' => $faker->numberBetween(1, 3),
'verified' => true,
'remember_token' => str_random(10),
'provider' => '',
'provider_id' => str_random(5)
];
});
Giving me this error:
A four digit year could not be found Data missing
I found the cause, but don't know how to fix it.
When I call the factory, I call it like that:
factory(User::class)->create(['role_id',2]);
If I call it like that:
factory(User::class)->create();
I get no more error.
But I really need to seed different kind of users...
Any idea???

have you tried using key value array in the create method:
factory(User::class)->create(['role_id' => 2]);

I might be late to the party, I was having the same problem and it turns out its because I provided a key without a value in the array returned.
get rid of 'provider' => ''.
As to the cause of the problem i really don't know but it has something to do with Carbon

I had the same issue when using mass assignment and it turned I had forgotten to wrap my array of inputs in the request helper function
That is I had
Model::create([form inputs]);
Instead of
Model::create(request([form inputs]);
Just incase someone comes across it.

I recently encounter the same problem, lately I found out that the only problem is I put an invalid value to the timestamp column type.
In my case I have column email_verified_at [timestamp]. I miss understood I put a string like company#example.com instead of date values, it should be now().

Related

Laravel validate array and exclude on specific array value

I have an array of values that I send together with other fields in a form to laravel.
The array contains a role_id field and a status field, the status can be I (Insert) U (update) D (Delete). When I validate the values in the array I want it to skip the ones where the status equals D. Otherwise I want it to validate.
private function checkValuesUpdate($userid = null)
{
return Request::validate(
[
'displayname' => 'required',
'username' => 'required',
'email' => ['nullable', 'unique:contacts,email' . (is_null($userid ) ? '' : (',' . $userid ))],
'roles.*.role_id' => ['exclude_if:roles.*.status,D', 'required']
]
);
}
I can't seem to get it to work. I've been searching all over the place for functional code as well as the Laravel documentation. But no luck so far. Has anybody ever done this?
Your problem comes from a misunderstanding of the exclude_if rule. It doesn't exclude the value from validation, it only excludes the value from the returned data. So it would not be included if you ran request()->validated() to get the validated input values.
According to the documentation, you can use validation rules with array/star notation so using the required_unless rule might be a better approach. (Note there's also more concise code to replace the old unique rule, and I've added a rule to check contents of the role status.)
$rules = [
'displayname' => 'required',
'username' => 'required',
'email' => [
'nullable',
Rule::unique("contacts")->ignore($userid ?? 0)
],
'roles' => 'array',
'roles.*.status' => 'in:I,U,D',
'roles.*.role_id' => ['required_unless:roles.*.status,D']
];

Laravel phpunit test nested eager loading

I have this nested relation im abit unsure how i assertJson the response within the phpunit test.
FilmController
public function show(string $id)
{
$film = Film::with([
'account.user:id,account_id,location_id,name',
'account.user.location:id,city'
])->findOrFail($id);
}
FilmControllerTest
public function getFilmTest()
{
$film = factory(Film::class)->create();
$response = $this->json('GET', '/film/' . $film->id)
->assertStatus(200);
$response
->assertExactJson([
'id' => $film->id,
'description' => $film->description,
'account' => $film->account->toArray(),
'account.user' => $film->account->user->toArray(),
'account.user.location' => $film->account->user->location->toArray()
]);
}
Obviously this isnt working because its returning every column for the user im a little unfamiliar with how you test nested relations with the code you need so im unsure with a toArray can anyone help out?
Testing is a place where you throw DRY (don't repeat yourself) out and replace it with hard coded solutions. Why? simply, you want the test to always produce the same results and not be bound up on model logic, clever methods or similar. Read this amazing article.
Simply hard code the structure you expect to see. If you changed anything in your model to array approach, the test would still pass even thou your name was not in the response. Because you use the same approach for transformation as testing. I have tested a lot of Laravel apps by now and this is the approach i prefers.
$account = $film->account;
$user = $account->user;
$location = $user->location;
$response->assertExactJson([
'description' => $film->description,
'account' => [
'name' => $account->name,
'user' => [
'name' => $user->name,
'location' => [
'city' => $location->city,
],
],
],
]);
Don't test id's the database will handle those and is kinda redundant to test. If you want to check these things i would rather go with assertJsonStructure(), which does not assert the data but checks the JSON keys are properly set. I think it is fair to include both, just always check the JSON structure first as it would likely be the easiest to pass.
$response->assertJsonStructure([
'id',
'description',
'account' => [
'id',
'name',
'user' => [
'id',
'name',
'location' => [
'id',
'city',
],
],
],
]);

Is there a way to set a validation on multiple inputs with similar name? Laravel 5.6

Is there a way to set a validation on multiple inputs with similar name? For ex -
public function rules()
{
return [
'zone1' => 'required|numeric',
'zone2' => 'required|numeric',
'zone3' => 'required|numeric',
];
}
Can I do something like 'zone*' => 'required|numeric'
You can use an asterisk as a wildcard but it may not be a great idea. With a rule like 'zone*' => 'required|numeric' as long as there's a single value that matches the condition the request will pass validation. For example, if a request has a valid value for zone2 but zone1 and zone3 are missing or non-numeric the validation will still pass

Laravel validation rules - optional, but validated if present

I'm trying to create a user update validation through form, where I pass, for example 'password'=>NULL, or 'password'=>'newone';
I'm trying to make it validate ONLY if it's passed as not null, and nothing, not even 'sometimes' works :/
I'm trying to validate as :
Validator::make(
['test' => null],
['test' => 'sometimes|required|min:6']
)->validate();
But it fails to validate.
Perhaps you were looking for 'nullable'?
'test'=> 'nullable|min:6'
Though the question is a bit old, this is how you should do it. You dont need to struggle so hard, with so much code, on something this simple.
You need to have both nullable and sometimes on the validation rule, like:
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'sometimes|nullable|between:8,20'
]);
The above will validate only if the field has some value, and ignore if there is none, or if it passes null. This works well.
Do not pass 'required' on validator
Validate like below
$this->validate($request, [
'username' => 'required|unique:login',
'password' => 'between:8,20'
]);
The above validator will accept password only if they are present but should be between 8 and 20
This is what I did in my use case
case 'update':
$rules = [
'protocol_id' => 'required',
'name' => 'required|max:30|unique:tenant.trackers'.',name,' . $id,
'ip'=>'required',
'imei' => 'max:30|unique:tenant.trackers'.',imei,' . $id,
'simcard_no' => 'between:8,15|unique:tenant.trackers'.',simcard_no,' . $id,
'data_retention_period'=>'required|integer'
];
break;
Here the tracker may or may not have sim card number , if present it will be 8 to 15 characters wrong
Update
if you still want to pass hardcoded 'NULL' value then add the
following in validator
$str='NULL';
$rules = [
password => 'required|not_in:'.$str,
];
I think you are looking for filled.
https://laravel.com/docs/5.4/validation#rule-filled
The relevant validation rules are:
required
sometimes
nullable
All have their uses and they can be checked here:
https://laravel.com/docs/5.8/validation#rule-required
if you want validation to always apply
https://laravel.com/docs/5.8/validation#conditionally-adding-rules
if you want to apply validation rules sometimes
https://laravel.com/docs/5.8/validation#a-note-on-optional-fields
if you want your attribute to allow for null as value too

Factories on Laravel 5.2 not working as expected

I have a very strange problem with Laravel 5.2 factories.
I have recently upgraded from Laravel 5.1 to 5.2 following the upgrade guide on the Laravel website. All works as exepected except one factory. Yes the others work ok. Here are two of the factories:
$factory->define(App\Client::class, function (Faker\Generator $faker) {
return [
'name' => $faker->company,
'building' => $faker->buildingNumber,
'street' => $faker->streetName,
'town' => $faker->city,
'postcode' => $faker->postcode,
'country' => 'UK',
'telephone' => $faker->phoneNumber,
'fax' => $faker->phoneNumber,
];
});
$factory->define(App\Shift::class, function (Faker\Generator $faker) {
return [
'client_id' => $faker->numberBetween($min = 1, $max = 15),
'user_id' => $faker->numberBetween($min = 1, $max = 15),
'start' => $faker->dateTimeBetween($startDate='now', $endDate='+60 days'),
'public' => $faker->boolean(),
];
});
The top factory works no problem but the second one doesn't run at all cause my db seed to throw an error because its not populating the client_id which is a foreign key.
The only difference between the two models is that the client model doesn't use timestamps where as the shift model does. Other than that they are identical.
I will keep plugging away but any help to shed light on this would be greatly received.
When you add your own constructor, are you making sure to call parent::__construct() inside it?

Categories