How to validate 2 form request in the same controller in laravel - laravel

I am validating a credit card, for which I created two form requests:
php artisan make:request StoreAmexRequest
php artisan make:request StoreVisaRequest
How can I use them in the same controller?
public function store(Request $request)
{
if ($request->credit_card['number'][0] == 3) {
new StoreAmexRequest(),
}
if ($request->credit_card['number'][0] == 4) {
new StoreVisaRequest(),
]);
}}
My code doesn't work, the $request variable doesn't receive it StoreAmexRequest()
I am making a credit card validator, the AMEX card validator is different from VISA cards, since AMEX is 15 digits and the CVV is 4 digits, and in VISA it is 16 digits.
It is necessary to use php artisan make:request since it is for an API that returns the response in JSON
\app\Http\Requests\StoreAmexRequest
public function authorize()
{
return true;
}
public function rules()
{
$year = date('Y');
return [
'credit_card.name' => ['required', 'min:3'],
'credit_card.number' => ['bail', 'required', 'min:15', 'max:16', new CredirCardRule],
'credit_card.expiration_month' => ['required', 'digits:2'],
'credit_card.expiration_year' => ['required', 'integer', 'digits:4', "min:$year"],
'credit_card.cvv' => ['required', 'integer', 'digits_between:3,4']
];
}
public function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
$validator->errors(),
]));
}

You could just use a single form request that validates both.
public function store(StoreCreditCardRequest $request)
{
YourCreditCardModel::create($request->validated());
}
And split the rules inside the form request
public function rules(): array
{
if ( $this->credit_card['number'][0] == 3 ) {
return $this->amexRules();
}
if ( $this->credit_card['number'][0] == 4 ) {
return $this->visaRules();
}
}
protected function amexRules(): array
{
return [
// your validation rules for amex cards
];
}
protected function visaRules(): array
{
return [
// your validation rules for visa cards
];
}

Related

Laravel unique validation if ID isn't in request

I want to do some validation for a field. Right now works for unique values, the problem is that on Update I get the same error. So I want to filter the request, if that post request contain ID field then this field shouldn't be unique.
public function rules()
{
return [
'customer_id' => 'required|unique:customers',
];
}
You can use Rule class' unique method for the update method
public function rules()
{
return [
'customer_id' => [
'required',
Rule::unique('customers')->ignore($customer->customer_id),
];
}
Laravel docs: https://laravel.com/docs/8.x/validation#rule-unique
For common rules() function it can be done as
use Illuminate\Validation\Rule;
class CustomerController extends Controller
{
protected function rules($customer)
{
return [
'customer_id' => [
'required',
Rule::unique('customers')->ignore($customer->exists ? $customer->customer_id : null),
];
}
public function store(Request $request)
{
$customer = new Customer;
$request->validate($this->rules($customer));
}
public function update(Request $request, Customer $customer)
{
$request->validate($this->rules($customer);
}
}
In my case I have a single method for store/update and I check If I have an ID or not. Also I added $customer = request()->all(); and ignore($customer['ID'] , that is for my specific case.
Laravel Docs warns against passing user controller request input to the ignore method
For your specific case you can do
$customer = !empty($request->input('ID') ? Customer::findOrFail($request->input('ID')) : new Customer;
//Then pass the customer to the rules()
$validated = $request->validate($this->rules($customer));

Validate specific rule - Laravel

I am using latest Laravel version.
I have requests/StoreUser.php:
public function rules() {
return [
'name' => 'required||max:255|min:2',
'email' => 'required|unique:users|email',
'password' => 'required|max:255|min:6|confirmed'
];
}
for creating a user.
Now I need and to update the user, but how can I execute only specific rules ?
For the example, if name is not provided, but only the email, how can I run the validation only for the email ?
This is easier than you thought. Make rules depend on the HTTP method. Here is my working example.
public function rules() {
// rules for updating record
if ($this->method() == 'PATCH') {
return [
'name' => 'nullable||max:255|min:2', // either nullable or remove this line is ok
'email' => 'required|unique:users|email',
];
} else {
// rules for creating record
return [
'name' => 'required||max:255|min:2',
'email' => 'required|unique:users|email',
'password' => 'required|max:255|min:6|confirmed'
];
}
}
You can separate your StoreUser request to CreateUserRequest and UpdateUserRequest to apply different validation rules. I think, this separation makes your code more readable and understandable.
Any HttpValidation request in laravel extends FormRequest that extends Request so you always have the ability to check request, auth, session, etc ...
So you can inside rules function check request type
class AnyRequest extends FormRequest
{
public function rules()
{
if ($this->method() == 'PUT'){
return [
]
}
if ($this->method() == 'PATH') {
return [
]
}
}
}
If things get complicated you can create a dedicated new HttpValidation request PostRequest PatchRequest
class UserController extends Controller
{
public function create(CreateRequest $request)
{
}
public function update(UpdateRequest $request)
{
}
}
See also the Laravel docs:
https://laravel.com/docs/5.8/validation
https://laravel.com/api/5.8/Illuminate/Foundation/Http/FormRequest.html

Laravel | Validate generated value

I have an endpoint for data create.
The request is "name". I need to generate "slug" and validate that slug is unique.
So, let's say
book_genres table.
id | name | slug
Request is ["name" => "My first genre"].
I have a custom request with a rule:
"name" => "string|unique:book_genres,name".
I need the same check for the slug.
$slug = str_slug($name);
How can I add this validation to my custom request?
Custom request class:
class BookGenreCreate extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
"name" => 'required|string|unique:book_genres,name',
];
}
}
So basically what you want to do is try to manipulate the request data before validation occurs. You can do this in your FormRequest class by overriding one of the methods that is called before validation occurs. I've found that this works best by overriding getValidatorInstance. You can then grab the existing data, add your slug to it and then replace the data within the request, all before validation occurs:
protected function getValidatorInstance()
{
$data = $this->all();
$data['slug'] = str_slug($data['name']);
$this->getInputSource()->replace($data);
return parent::getValidatorInstance();
}
You can also add the rules for your slug to your rules method as well:
public function rules()
{
return [
"name" => 'required|string|unique:book_genres,name',
"slug" => 'required|string|unique:book_genres,slug',
];
}
So your class will look something like this:
class BookGenreCreate extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|string|unique:book_genres,name',
'slug' => 'required|string|unique:book_genres,slug',
];
}
protected function getValidatorInstance()
{
$data = $this->all();
$data['slug'] = str_slug($data['name']);
$this->getInputSource()->replace($data);
return parent::getValidatorInstance();
}
}
Now when the request comes through to your controller, it will have been validated and you can access the slug from the request object:
class YourController extends Controller
{
public function store(BookGenreCreate $request)
{
$slug = $request->input('slug');
// ...
}
}
You can add the 'slug' to the request, then use validations as usual.
rules() {
// set new property 'slug' to the request object.
$this->request->set('slug', str_slug($request->name));
// rules
return [
'name' => 'string|unique:book_genres,name',
'slug' => 'string|unique:book_genres,slug'
]
}

Laravel 5.6 FormRequest validation

I have set of input fields to be validated. I have removed commas (since user enters comma as thousand separator) before validation takes place. But it still complains that the number is not numeric.
class UpdateFamilyExpense extends FormRequest
{
public function authorize()
{
return true;
}
public function sanitize()
{
$attributes = $this->all();
for ($i=1; $i<=15; $i++)
{
$attributes['e'.$i] = str_replace(',', '', $attributes['e'.$i]);
}
$this->replace($attributes);
}
public function rules()
{
$this->sanitize();
return [
'e1' => 'required|numeric',
];
}
public function messages()
{
return [
'e1.required' => 'required',
'e1.numeric' => 'must be a numeric',
];
}
}
I cannot figure out where I am wrong. Can someone help me figure out what I am missing here?
Override prepareForValidation as:
protected function prepareForValidation()
{
$this->sanitize();
}

change value of $request before validation in laravel 5.5

I have a form in route('users.create').
I send form data to this function in its contoller:
public function store(UserRequest $request)
{
return redirect(route('users.create'));
}
for validation I create a class in
App\Http\Requests\Panel\Users\UserRequest;
class UserRequest extends FormRequest
{
public function rules()
{
if($this->method() == 'POST') {
return [
'first_name' => 'required|max:250',
It works.
But How can I change first_name value before validation (and before save in DB)?
(Also with failed validation, I want to see new data in old('first_name')
Update
I try this:
public function rules()
{
$input = $this->all();
$input['first_name'] = 'Mr '.$request->first_name;
$this->replace($input);
if($this->method() == 'POST') {
It works before if($this->method() == 'POST') { But It has not effect for validation or for old() function
Override the prepareForValidation() method of the FormRequest.
So in App\Http\Requests\Panel\Users\UserRequest:
protected function prepareForValidation()
{
if ($this->has('first_name'))
$this->merge(['first_name'=>'Mr '.$this->first_name]);
}
Why not doing the validation in the controller? Than you can change things before you validate it and doing your db stuff afterward.
public function store(Request $request)
{
$request->first_name = 'Mr '.$request->first_name;
Validator::make($request->all(), [
'first_name' => 'required|max:250',
])->validate();
// ToDo save to DB
return redirect(route('users.create'));
}
See also https://laravel.com/docs/5.5/validation
Simply use
$request->merge(['New Key' => 'New Value']);
In your case it can be as follows for saving
$this->merge(['first_name'=>'Mr '.$this->first_name]);

Resources