Trim inputs before validation in the Requests - Laravel - validation

I am using laravel 5.1 and I am validating the inputs in a Requests as below,
public function rules()
{
return [
'first_name' => 'required|min:2'
];
}
Here if the first_name = ' s' validation passes which i not expected, I need to trim the inputs before the validation happens.
I tried like this,
public function rules()
{
$this->replace(array_map('trim', $this->all()));
return [
'first_name' => 'required|min:2'
];
}
But I am getting the same result.
I saw something related to laravel 4.x (LINK)
How to get this done?
NOTE: I am not validating in the controller by creating a validation instance, I am using Request to validate the request.

try this, I hope this might help you.
public function rules()
{
$input = $this->all();
$input['first_name'] = trim($input['first_name']);
$this->replace($input);
return [
'first_name' => 'required|min:2',
];
}

Related

Find data before validate form request laravel

I want to update the data using the request form validation with a unique email role, everything works normally.
Assume I have 3 data from id 1-3 with url:
127.0.0.1:8000/api/user/update/3
Controller:
use App\Http\Requests\Simak\User\Update;
...
public function update(Update $request, $id)
{
try {
// UPDATE DATA
return resp(200, trans('general.message.200'), true);
} catch (\Exception $e) {
// Ambil error
return $e;
}
}
FormRequest "Update":
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->id,
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
but if the updated id is not found eg:
127.0.0.1:8000/api/user/update/4
The response gets The email has already been taken.
What is the solution so that the return of the data is not found instead of validation first?
The code looks like it should work fine, sharing a few things below that may help.
Solution 1: Check if $this->id contains the id you are updating for.
Solution 2: Try using the following changes, try to get the id from the URL segment.
public function rules()
{
return [
'user_akses_id' => 'required|numeric',
'nama' => 'required|max:50',
'email' => 'required|email|unique:users,email,' . $this->segment(4),
'password' => 'required',
'foto' => 'nullable|image|max:1024|mimes:jpg,png,jpeg',
'ip' => 'nullable|ip',
'status' => 'required|boolean'
];
}
Sharing one more thing that may help you.
Some person uses Request keyword at the end of the request name. The Update sounds generic and the same as the method name you are using the request for. You can use UpdateRequest for more code readability.
What I understand from your question is, you need a way to check if the record really exists or not in the form request. If that's the case create a custom rule that will check if the record exists or not and use that rule inside your request.
CheckRecordRule
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class CheckRecordRule implements Rule
{
protected $recordId;
public function __construct($id)
{
$this->recordId = $id;
}
public function passes($attribute, $value)
{
// this will check and return true/false
return User::where('id', $this->recordId)->exists();
}
public function message()
{
return 'Record not found.';
}
}
Update form request
public function rules()
{
return [
'email' => 'required|email|unique:users,email,' . $this->id.'|'. new CheckRecordRule($this->id),
];
}
So when checking for duplicate it will also check if the record really exists or not and then redirect back with the proper message.

Laravel validation exists in this table OR that table

I need to validate the existence of an API request parameter
but check it in one of two tables, users and teachers
something like this
$rules = ['apiToken' => 'required|string|min:70|exists:users,api_token ((OR)) exists:teachers,api_token']
is there a way to achieve this using Laravel validator?
For something like this you will probably need to use custom validation:
$rules = [
'apiToken' => [
'required', 'string', 'min:70', function ($attribute, $value, $fail) {
if (!DB::table('users')->where('api_token', $value)->exists() || !DB::table('teachers')->where('api_token', $value)->exists()) {
return $fail("The provided $attribute is not valid.");
}
}
]
];
You can change the returned error message by editing the text passed to the $fail function.

Validation of array in laravel

I am building a small application in Laravel 5.6 where I am having an api which takes an array in format [1,2,5,90,25] I want to validate as required field in my validation rule.
I tried creating a request and validating the same as:
public function rules()
{
return [
'ProjectType.*'=> 'required',
]
}
public function messages()
{
return [
'projectType.*.required' => 'Project type is required',
];
}
But this thing is not working out, even if an empty array [] is being passed it accepts it.
How can we achieve these kind of array format
You must validate at the top level of the array, you may want this validation:
public function rules()
{
return [
'ProjectType'=> 'required|array',
'ProjectType.*'=> 'required',
]
}
public function messages()
{
return [
'projectType.*.required' => 'Project type is required',
];
}

Laravel action when form validation generates error

I am working with a form request file like this:
ProjectCreateRequest.php
public function rules()
{
$project_name = $this->project_name;
$meta_activity = $this->meta_activity;
return [
'project_name' => 'required|max:255|unique:projects',
'customer_name' => 'required|max:255',
'otl_project_code' => 'sometimes|max:255|unique:projects,otl_project_code,NULL,id,meta_activity,'.$meta_activity,
'estimated_start_date' => 'date',
'estimated_end_date' => 'date',
'LoE_onshore' => 'numeric',
'LoE_nearshore' => 'numeric',
'LoE_offshore' => 'numeric',
'LoE_contractor' => 'numeric',
'revenue' => 'numeric',
'win_ratio' => 'integer'
];
}
There is the otl_project_code that must be unique with the meta_activity.
In case someone enters a pair of otl_project_code and meta_activity that already exists, it goes back to the create page with the error written below.
I would like to get instead that in the controller, I can catch this information, do something on the database then redirect to an update url.
Because I am working with a form validation request file, everything is entered in my controller like this:
public function postFormCreate(ProjectCreateRequest $request)
and I don't know how to catch this specific error in my controller to execute some actions with all the fields I submitted and not go back to the create page. Of course, this needs to happen only when there is the specific error I mentionned above.
Override the FormRequest response function in your ProjectCreateRequest:
/**
* Get the proper failed validation response for the request.
*
* #param array $errors
* #return \Symfony\Component\HttpFoundation\Response
*/
public function response(array $errors)
{
if ($this->expectsJson()) {
return new JsonResponse($errors, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
That's the public response on the FormRequest class so you can write your own logic to perform DB queries and redirect where needed.

unique value with custom request laravel 5.3

i have custom request in laravel ..
this is the code
public function rules()
{
if($this->ajax())
{
return [];
}
else
{
return
[
'username'=> 'required|min:3|max:30|unique:users',
'password'=> 'required|min:6',
'email'=>'required|min:3|max:35|unique:users',
'permission'=>'required',
'phone'=>'required',
'division'=>'required',
];
}
}
and i need to to ignore the current id from validation
i tried this
public function rules()
{
if($this->ajax())
{
return [];
}
else
{
return
[
'username'=> 'required|min:3|max:30|unique:users,id'.$this->id,
'password'=> 'required|min:6',
'email'=>'required|min:3|max:35|unique:users',
'permission'=>'required',
'phone'=>'required',
'division'=>'required',
];
}
}
but its ignoring the whole user name from validation not just the current id ..
Use auth()->user()->id instead of $this->id to get current user's ID.
Also, I'm not sure about the syntax you're using when trying to add ignoring ID. From unique() rule docs:
To instruct the validator to ignore the user's ID, we'll use the Rule class to fluently define the rule. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);

Resources