I'm building an API, one of the db table Person have 52 columns and most of them are required t don't think the way I'm doing is right
public function store() {
if (! input::get('name') or ! input::get('age') or ! input::get('phone') or ! input::get('address') and so on till the 52 field) {
return "Unprocessable Entity";
}
return "Validated";
}
And how to properly validate all the required fields
Thank You
You can simply write your validation rules and messages within a Request file and can call directly within your store function like as
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Validation\Rule;
/**
* Class YourFileRequest
* #package App\Http\Requests
*/
class YourFileRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
];
}
/**
* Get the custom validation messages that apply to the request.
*
* #return array
*/
public function messages()
{
return [
'title.required' => 'Please enter title',
'title.max' => 'Please enter max value upto 255',
'body.required' => 'Please enter body',
];
}
}
within your controller
use App\Http\Requests\YourFileRequest;
......
public function store(YourFileRequest $request)
{
//Your storing logic
}
You can do it in two ways:
The first one is
$this->validate($request,['email'=>'required|email|unique']);
Secondly, you can create a separate ValidationRequest by using the following command:
php artisan make:request StoreRequest
Related
I have a question about Laravel validation. I have two number <input> fields like:
I want to create a rule in the "Request" file from App\Requests\MyRequest.php that requires the value from the second input field to be greater than the first input field and that both fields must have a value greater than 0.
How should I code this? Does Laravel validation support this?
You can add validations in app/Http/Requests by running php artisan make:request MyRequest something like below:
<?php
namespace App\Http\Requests;
class MyRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'first_field' => 'min:0',
'second_field' => 'min:'.$this->first_field,
];
}
}
You can find more about validations here
I'm using laravel 5.5
I have a Request that I've built but the required rule is not working correctly.
Route
Route::get('v1/learning_centre/user/{userId}/course/list', 'API\LearningCentre#userCourses');
Controller
public function userCourses(GetUserCourses $request)
{
$courses = User::findOrFail($request->userId)
->courses()
->get();
return new CourseResourceCollection($courses);
}
Request
namespace App\Http\Requests\LearningCentre;
use Illuminate\Foundation\Http\FormRequest;
class GetUserCourses extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'userId' => 'required|integer'
];
}
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'userId.required' => 'A User is required',
];
} }
If I turn off the required rule I can get to the controller. If I have the required rule in the request I get a 302. I am passing in a valid userId in phpunit. Without the request rules my code works as intended.
Any ideas?
You should be using route model binding to validate a required GET parameter in this situation, not a FormRequest class, which, as the name should indicate, are intended for form requests.
Your route:
Route::get('v1/learning_centre/user/{user}/course/list', 'API\LearningCentre#userCourses');
Your controller:
public function userCourses(User $user) {
If a user ID is missing (or an invalid one used), your controller will automatically throw a ModelNotFoundException, which Laravel by default returns as a 404.
Is it possible to use my custom validation rule in a validation request file?
i want to use my custom rule called EmployeeMail
here is the code of the request file
class CoachRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$rules = [];
if ($this->isMethod('post') ) {
$rules = [
'name' => 'required|string',
'email' => 'required|email|employeemail', <<<--- this
'till' => 'required|date_format:H:i|after:from',
];
}
//TODO fix this
//TODO add custom messages for every field
return $rules;
}
}
it gives me an error when i try to use it like this
Method [validateEmployeemail] does not exist.
code of custom rule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class EmployeeMail implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
// If mail is that of an employee and not a student pass it
return preg_match("/#test.nl$/", $value) === 1;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'Email is geen werknemers mail';
}
}
can i only use this custom rule like this?
$items = $request->validate([
'name' => [new FiveCharacters],
]);
Rutvij Kothari answered the question in the comments.
It seems you are validating string with a regular expression, the same logic can be achieved by regex buit-in validation method. Check it out. laravel.com/docs/5.5/validation#rule-regex No need to create your own validation rule. – Rutvij Kothari
If you want to use your validation pass it into an array. like this. 'email' => ['required', 'email', new employeemail]
I've got the following request validation:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class OwnerEstate extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'firstname' => 'required_if:type,individual',
'secondname'=> 'required_if:type,individual',
'lastname' => 'required_if:type,individual',
'pin' => 'required_if:type,individual|digits:10',
'name' => 'required_if:type,legal-entity',
'eik' => 'required_if:type,legal-entity|digits:9'
];
}
}
And when the type is not individual it still checks for the 'digits:10' validation of the pin and returns an error. How do I disable the other validation if required_if validation does not require the field. (I'm using Laravel 5.5)
digits:10 is completely separate from required_if, so it will validate whether or not the field is required. However, if you want to also allow null or empty values (assuming the field is not required), you can add the rule nullable.
https://laravel.com/docs/5.5/validation#rule-nullable
I have a CategoryRequest.php file and a unique validation for field 'name'.
When I use the form to create, it works, so it prevents from inserting a category with the same name.
The problem is when try to update it, is says: 'The name has already been taken.' or if I try the code below, it says: 'Undefined Variable: id'.
How can I update and it ignores its own name when validating?
Here is my code:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CategoryRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|unique:categories,name,'.$id.',id'
];
}
}
change this:
return [
'name' => 'required|unique:categories,name,'.$id.',id'
];
to this:
return [
'name' => 'required|' . Rule::unique('categories')->ignore('category')
];
or this:
return [
'name' => ['required', Rule::unique('categories')->ignore('category')]
];