How to test min/max length with Laravel Feature tests - laravel-5

I am trying to validate a feature test. Here is my controller:
$attributes = $request->validate([
'name' => 'required',
'description' => 'required',
'address' => 'required',
'city' => 'required',
'state' => 'required|max:2',
'zip' => 'required|min:5',
]);
Location::create($attributes);
return redirect('/locations', 301);
I am saying that state can only have a max length of 2 characters.
My test looks like this:
$this->withExceptionHandling();
$user = factory(User::class)->create();
$location = factory(Location::class)->raw(['state' => 'qwerty']);
$response = $this->actingAs($user)->post('/locations', $location);
$response->assertStatus(302);
$response->assertSessionHasErrors([
'state' => 'The state may not be greater than 2 characters.'
]);
And that test will pass.
However if I change it to this:
...
$location = factory(Location::class)->raw(['state' => 'AZ']);
....
Expected status code 302 but received 301.
Failed asserting that false is true.
It will fail. I am confused, since I want a 2 character state. Any suggestions are greatly appreciated!
EDIT
I have also tried to add the messages method to my controller to return exactly that error message with no luck.
public function messages()
{
return [
'state.max' => 'The state may not be greater than 2 characters.',
];
}

Related

error getting a user existing in laravel sanctum

I have a error, I'm using sanctum and I want to check that the email does not exist
the if returns an empty array but the if is satisfied because it returns true
$mail = $request->input(['email']);
if ($search = User::where('email', $mail)->get()) {
return response()->json(['msg' => 'account already exist'], 409);
} else {
$validate = $request->validate([
'name' => 'required|string|',
'email' => 'required|string',
'password' => 'required|string'
]);
}
any solution?
Why not use the Laravel validation since this looks more like validation, so something like:
$request->validate([
'name' => 'required|string|',
'email' => 'required|string|email|unique:users,email',
'password' => 'required|string'
]);
with this you don't need to do an if else. You can check the Laravel docs on https://laravel.com/docs/8.x/validation#introduction for more details

Laravel one validation function for Store and Update

I am trying to have one validation function for both store and update. So I don't repeat code. It works well. The problem is testing 'unique'. I worked around with this idea. But feels long-winded. Is there a better way to do it?
I want to check for unique at the store.
At update, unique check ignores own id.
I don't want different validations like I did as the user will be
first notified of the unique error, he will fix it. then something
else might be wrong and he has to fix again.
.
public function validateRequest($request){
if($request->method() == "PUT")
{
$val = $this->validate($request, [
'name' => 'unique:customers,id',
'phone' => 'unique:customers,id',
]);
}
if($request->method() == "POST"){
$val = $this->validate($request, [
'name' => 'unique:customers',
'phone' => 'unique:customers'
]);
}
$validation = $this->validate($request, [
'name' => 'required',
'phone' => 'required|integer|gt:0',
'phone2' => 'nullable|integer|gt:0|',
'email' => 'email|nullable',
'note' => 'nullable',
],
[
'phone.integer' => "Invalid phone format. Use international format. Eg: 971550000000",
'phone2.integer' => "Invalid phone format. Use international format. Eg: 971550000000",
'required' => "Required Field",
]);
return $validation;
}

Custom request validators for Multiple arrayed inputs

I have 1 form, with multiple inputs. each section can have multiple inputs, I want to create a Form Validator inside Requests for they, but don't know how to do it... This is currently how I am doing it:
public function postCreateResume(Request $request, Resume $resume, Education $education)
{
/*
* begin a transaction, because we
* are doing multiple queries
*/
DB::beginTransaction();
/*
* first we must create the resume, then we
* can use the id for the following rows
*/
$this->validate($education, [
'resume_title' => 'required',
'expected_level' => 'required',
'salary' => 'required',
'work_location' => 'required',
'year_experience' => 'required',
'about' => 'required',
]);
$resume->name = $request['resume_title'];
$resume->work_level = $request['expected_level'];
$resume->salary = $request['expected_salary'];
$resume->country = $request['work_location'];
$resume->total_experience = $request['year_experience'];
$resume->about = $request['about'];
$resume->save();
// a user can have multiple educations on their cv
foreach($request->input('education') as $education){
$this->validate($education, [
'institution' => 'required',
'degree' => 'required',
'year_begin' => 'required',
'year_finish' => 'required',
'about' => 'required',
]);
// passed our checks, insert
$education->resume_id = $resume->id;
$education->user_id = Auth::user()->id;
$education->institute = $education['institution'];
$education->degree = $education['degree'];
$education->summary = $education['about'];
$education->started = $education['year_begin'];
$education->ended = $education['year_finish'];
if(!$education->save()){
DB::rollback();
return redirect()->back()->withErrors("There was an error creating this resume")->withInput();
}
}
// a user can have multiple employment on their cv
foreach($request->input('experience') as $employment){
$this->validate($employment, [
'company' => 'required',
'title' => 'required',
'country' => 'required',
'year_begin' => 'required',
'year_finish' => 'required',
'notes' => 'required',
]);
// passed our checks, insert
$employment->resume_id = $resume->id;
$employment->user_id = Auth::user()->id;
$employment->name = $employment['title'];
$employment->company = $employment['company'];
$employment->country = $employment['country'];
$employment->started = $employment['year_begin'];
$employment->ended = $employment['year_finish'];
$employment->summary = $employment['notes'];
if(!$employment->save()){
DB::rollback();
return redirect()->back()->withErrors("There was an error creating this resume")->withInput();
}
}
return redirect()->back()->withSuccess("You have created a resume")->withInput();
}
Notice I have the validate inside each of the foreach in case the user has chosen more than 1 (in this example) work experience, or education, what I am trying to do is move the $this->validate inside the Requests folder, how can I achieve this?
I am using a foreach because I can have unlimited sections, see the image as to why;
Since laravel 5.4 you can pass arrays to the validator itself, for exaple
<input name="myarray[0]['test'] type="text">
Can now be validated like so
$this->validate($request, [
'myarray.*.test' => 'required'
]);
https://laravel.com/docs/5.4/validation#validating-arrays
Validating array based form input fields doesn't have to be a pain. For example, to validate that each e-mail in a given array input field is unique, you may do the following:
$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);
Likewise, you may use the * character when specifying your validation messages in your language files, making it a breeze to use a single validation message for array based fields:
'custom' => [
'person.*.email' => [
'unique' => 'Each person must have a unique e-mail address',
]
],

Validate whether multiple fields are unique simultaneously in laravel 5

This my request class rules.
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'unique:event_cals,eventDate,NULL,id,venue,$request->venue,time,$request->time'
];
I want to validate a rule like below.
'eventDate' && 'venue' && 'time' => 'unique'
There I need to check if there any row without same eventDate, venue and time altogether. Anyone knows how to declare such a rule?
This is the snapshot of db table.
Here is the possible solution:
<?php
return [
'title' => 'required|unique:event_cals,title',
'eventDate' => 'required|date|after:yesterday',
'venue' => 'required',
'time' => 'required',
'type' => 'required',
'event_date' => "unique:event_cals,event_date,NULL,id,venue,{$request->venue},time,{$request->time}",
];
I again want to highlight that; if you want that validator to work, you should make sure that the event_date and time should be correctly formatted.
An example unique check with additional wheres from our running project's update requests:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = $this->route('money');
return $rules = [
'name' => "required|string|min:3|max:255|unique:moneys,name,{$id},id,deleted_at,NULL,access,public",
];
}

$this->validation custom redirect

I have a form with four tab so after validation it redirect me on first tab always, but i want it redirect me on that which have error message
Here is my code
$this->validate($request,
[
'name' => 'required|min:3|alpha_spaces',
'date_of_birth' => 'required|date|date_format:"Y-m-d"',
'place_of_birth' => 'required',
'nationality' => 'required',
'address' => 'required',
'port_name' => 'required',
'contact_number' => 'required|digits_between:8,15|numeric',
'religion' => 'required',
'education_level' => 'required',
'marital_status' => 'required',
'interview_method' => 'required',
'can_be_interviewed_via' => 'required',
'date_to' => 'required',
'date_from' => 'required',
'country' => 'required',
]);
and for redirect i m using on every tab i m using submit button with hidden filed selecttab
if ($data['selecttab'] == 'tab0') {
return redirect("fdws/".$id."/edit?tab=tab0");
}elseif($data['selecttab'] == 'tab1'){
return redirect("fdws/".$id."/edit?tab=tab1");
}elseif($data['selecttab'] == 'tab2'){
return redirect("fdws/".$id."/edit?tab=tab2");
}else{
return redirect("fdws/".$id."/edit?tab=tab3");
}
When no validation apply it work fine
Before you call your `$this->validate($request, ...` set `$redirect` to the result of your `if ($data['selecttab'] == 'tab0') { ...` statement. Therefore, I suggest first do your if statement and have a variable named `$redirect` that catches the result of the if statment
if ($data['selecttab'] == 'tab0') {
$redirect = "fdws/".$id."/edit?tab=tab0";
}elseif($data['selecttab'] == 'tab1'){
$redirect = "fdws/".$id."/edit?tab=tab1";
}elseif($data['selecttab'] == 'tab2'){
$redirect = "fdws/".$id."/edit?tab=tab2";
}else{
$redirect = "fdws/".$id."/edit?tab=tab3";
}
And then `$this->validate(...)`.
Scratch that! I made a big mistake. According to official Laravel 5.0 documentation, and also looking at the Illuminate\Foundation\ValidatesRequests trait, when using Controller Validation, it is NOT possible to just chose the redirect route without modification to the traits or other codes. I think using Form Request will give you the power you want with a lot less hassle.
Solution found,
I done like that and its working fine :)
$validator = Validator::make($request->all(), [
'can_be_interviewed_via' => 'required',
]);
if ($validator->fails()) {
return redirect("fdws/".$id."/edit?tab=tab3")
->withErrors($validator)
->withInput();
}
In Laravel 5 use Middleware as helpers for controllers and routes. This will help you a lot.

Resources