I have a form which performs the inserting function, the related method is :
public function addthread(Request $request) {
//validate
$this->validate($request, [
'title' => 'required|unique:thread|max:255',
'num_opt' => $this->checkOpt($request),
]);
}
I want to use a custom function to validate the num_opt elements,:
protected function checkOpt($request, Validator $validator) {
//$num_opt = $request->input('num_opt');
if ($request->has('$num_opt')) {
//$validator->errors()->add ??
How to customize the error message?
}
//die();
}
Questions:
Is the above code practice is wrong or not?
How can I access $validator and customize the error message in the checkOpt function?
Related
In my input form, I have two fields; momentFrom & momentTo. I need to put a validation which gives error message if any of the following criteria fails.
momentFrom is greater than or equal to momentTo.
momentFrom is less than now.
My code for storing the data:
public function store(Request $request, Requisition $requisitionObj) {
$momentFrom = strtotime($request->txtTravelDate . " " . $request->txtTimeFrom);
$momentTo = strtotime($request->txtTravelDate . " " . $request->txtTimeTo);
$timeValidation = $requisitionObj->validateTiming($momentFrom, $momentTo);
if ($timeValidation['error']) {
echo 'ERROR: ' . $timeValidation['message'];
return view('requisitions.create');
} else {
/* store form data into requisition object */
$requisitionObj->travel_date = $request->txtTravelDate;
$requisitionObj->moment_from = $momentFrom;
$requisitionObj->moment_to = $momentTo;
$requisitionObj->save();
return redirect()->route('requisitions.index');
}
}
I have seen laravel custom validation rules where only one field can be validated at a time. But in my scenario I need to check both fields at a time depending on each other. How can I achieve this?
Thanks for any help in advance!
Creating new Rule Class
You can create your custom rule with the artisan command: php artisan make:rule YourRuleNamethis will create a new Rule Class file into the Rules folder.
By default the created file contains a constructor, a passes method and a message method.
Rules Logic
If you have some complicated rules where you need the request or some models, you can pass them via the constructor.
public function __construct(Request $request, User $user, ....)
{
//save them into class variables to access them later
$this->request = $request;
$this->user = $user;
}
Otherwise you can directly put your validation logic into the passes method:
public function passes($attribute, $value){
//some code
return #myCondition
}
Last you are able to specify the message if the validation fails.
public function message()
{
return 'Your message';
}
To use your rule simply add it to your rules array:
$rules = [
'my_attribute' => [new MyCustomRule(),...],
]
At last, I have solved this problem using FormRequest and AppServiceProvider. Thought this would help others who come to this place.
First I have created FormRequest validator using following artisan command.
php artisan make:request StoreRequisition
Then added primary validation rules and messages into it.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreRequisition extends FormRequest {
public function authorize() {
return true;
}
public function rules() {
$rules = [
'txtTravelDate' => 'required|date_format:Y-m-d|after_or_equal:today',
'txtTimeFrom' => 'required|date_format:H:i|travel_time_validate',
'txtTimeTo' => 'required|date_format:H:i',
];
return $rules;
}
public function messages() {
return [
'txtTravelDate.required' => 'Travel date is required!',
'txtTravelDate.date_format' => 'Invalid format for Travel Date!',
'txtTravelDate.after_or_equal' => 'Travel Date should be today or later!',
'txtTimeFrom.required' => 'Time From is required!',
'txtTimeFrom.date_format' => 'Invalid format for Time From!',
'txtTimeFrom.travel_time_validate' => 'Invalid time selected!',
'txtTimeTo.required' => 'Time To is required!',
'txtTimeTo.date_format' => 'Invalid format for Time To!',
'listFunction.required' => 'Department to be selected!',
'txtPickLoc.required' => 'Pickup Location is required!',
'txtDropLoc.required' => 'Drop Location is required!',
'listPurpose.required' => 'Travel Purpose to be selected!'
];
}
}
Then inside app\Providers\AppServiceProvider, added the extra validation logic.
public function boot() {
Validator::extend(
'travel_time_validate',
function ($attribute, $value, $parameters, $validator) {
$inputs = $validator->getData();
/* convert time to moments */
$momentFrom = strtotime($inputs['txtTravelDate'] . " " . $inputs['txtTimeFrom']);
$momentTo = strtotime($inputs['txtTravelDate'] . " " . $inputs['txtTimeTo']);
$result = true;
if ($momentFrom >= $momentTo) {
$result = false;
}
return $result;
}
);
}
My Controller:
public function store(StoreRequisition $request, Requisition $requisitionObj) {
$validatedData = $request->validated();
/* store form data into requisition object */
$requisitionObj->requester_id = Auth::user()->id;
$requisitionObj->travel_date = $request->txtTravelDate;
$requisitionObj->time_from = $request->txtTimeFrom;
$requisitionObj->time_to = $request->txtTimeTo;
$requisitionObj->purpose_id = $request->listPurpose;
/* Finally save the record into the database */
$requisitionObj->save();
return redirect()->route('requisitions.index');
}
Example how make custom rule for validation in Laravel 8.x / Lumen 8.x.
public static function rules(){
return [
'number' => [
'required', 'min:1', 'max:30', 'string', self::testNumber(),
],
];
}
public static function testNumber(){
return function($attribute, $value, $fail){
if ($value === 'foo'){
$fail('The '.$attribute.' is invalid.');
}
};
}
In request I got attribute that defines validation rules and flow. Let's say it is account_type: business, personal.
Each value changes validation flow and requires different attributes to be present ir request.
Let's say I have following custom rules methods:
public function validateAccountTypeBusiness($attribute, $value, $parameters, Validator $validator)
{
// check is present:
// Company address
// VAT number
}
public function validateAccountTypePersonal($attribute, $value, $parameters, Validator $validator)
{
// check is present:
// User mobile phone
}
Since each rule requires more than single attribute to be presented in this request depending on account type ( vat number, company name, etc ) returning false would be not informative to user because generated response notices that account type is invalid without any details which actual attributes is missing.
The question is: how I can append more rules to be validated in this validation custom rule?
Following not working:
public function validateAccountTypeBusiness($attribute, $value, $parameters, Validator $validator)
{
$validator->addRules([
'company_address' => 'required|string',
'vat_number' => 'required',
]);
}
If you follow Complex Conditional Validation, you can validate using the following way
Step 1: Create Validator instance with static rules which would be same in both the cases(business or personal account) like name,check,phone,email,etc.
$v = Validator::make($data, [
'email' => 'required|email',
'name' => 'required|alpha',
'phone' => 'required|numeric',
'check' => 'required' //common in both account type
//add more rules as required
]);
Step 2: Add specific rules with condition
$v->sometimes('VAT', 'required|max:50', function ($input) {
return $input->account_type == 'business';
});
$v->sometimes('Company_address', 'required|max:500|alpha', function ($input) {
return $input->account_type == 'business';
});
$v->sometimes('user_mobile', 'required|numeric', function ($input) {
return $input->account_type == 'personal';
});
Parameters for sometimes() method :
The first argument passed to the sometimes method is the name of the
field we are conditionally validating. The second argument is the
rules we want to add. If the Closure passed as the third argument
returns true, the rules will be added.
As per my understanding, Custom validation rule can be used for only one parameter & you're trying to club them together.
This is one of many ways to approach your problem. Hope it helps.
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AccountController extends Controller
{
/**
* Store a new user account.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
if($request->input('account_type' == 'business') {
// Validation for business account
$validator = Validator::make($request->all(), [
'company_address' => 'required|string',
'vat_number' => 'required',
]);
}
else {
// Validation for personal account
$validator = Validator::make($request->all(), [
'contact_number' => 'required',
]);
}
if ($validator->fails()) {
return redirect('account/create')
->withErrors($validator)
->withInput();
}
// Store the user account...
}
}
Reference -
Manually creating validators -
https://laravel.com/docs/5.4/validation#manually-creating-validators
I'm building an api using laravel, the issue is when the client requests my api by calling create() function, and the create()function will call a getValidatedData() function which I want to return validation errors to the client if validation fails or return the validated data to insert database if validation passes, my getValidatedData function is like below so far
protected function getValidatedData(array $data)
{
// don't format this class since the rule:in should avoid space
$validator = Validator::make($data, [
'ID' => 'required',
'weight' => 'required',
]);
if ($validator->fails()) {
exit(Response::make(['message' => 'validation fails', 'errors' => $validator->errors()]));
}
return $data;
}
I don't think exit() is a good way to return the errors message to clients. are there any other ways I can return the laravel Response to clients directly in an inner function. use throwing Exception?
This was what worked for me in Laravel 5.4
protected function innerFunction()
{
$params = [
'error' => 'inner_error_code',
'error_description' => 'inner error full description'
];
response()->json($params, 503)->send();
}
What you can do is using send method, so you can use:
if ($validator->fails()) {
Response::make(['message' => 'validation fails', 'errors' => $validator->errors()])->send();
}
but be aware this is not the best solution, better would be for example throwing exception with those data and adding handling it in Handler class.
EDIT
As sample of usage:
public function index()
{
$this->xxx();
}
protected function xxx()
{
\Response::make(['message' => 'validation fails', 'errors' => ['b']])->send();
dd('xxx');
}
assuming that index method is method in controller you will get as response json and dd('xxx'); won't be executed
You can use this method
public static function Validate($request ,$rolse)
{
// validation data
$validator = Validator::make($request->all(),$rolse);
$errors = $validator->getMessageBag()->toArray();
$first_error = array_key_first($errors);
if (count($errors) > 0)
return 'invalid input params , ' . $errors[$first_error][0];
return false;
}
in controller :
$validate = ValidationHelper::Validate($request,
['title' => 'required']);
if ($validate)
return response()->json(['message' =>'validation fails' , 'error'=> $validate], 403);
I'm building an API in Laravel, and am using a custom request to validate the inbound data. My problem is that I'm not sure how I 'catch' the validation errors to shape the response.
Here's what I have so far.
Register method wrapped in a transaction:
//Create User Request extends standard request. Handles Validation
public function __construct(CreateUserRequest $request){
$this->request = $request;
}
public function register()
{
try{
$array = DB::transaction(function(){
$email = $this->request->input('email');
$password = $this->request->input('password');
$companyName = $this->request->input('companyName');
$userName = $this->request->input('name');
$country = $this->request->input('country');
$company = Company::create([
'name' => $companyName,
'active'=>true,
'country_id'=>$country
]);
$user = User::create([
'company_id' => $company->id,
'name'=>'admin',
'email' => $email,
'password' => $password,
'active' =>true
]);
if( !$company || !$user )
{
throw new \Exception('User not created for account');
}
return compact('company', 'user');
});
$token = JWTAuth::fromUser($array['user']);
return Response::json(compact('token'));
}
catch( Exception $e )
{
return Response::json(['error' => $e->getMessage() ], HttpResponse::HTTP_CONFLICT );
}
}
The form request looks like this:
class CreateUserRequest 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 [
'email' => 'required|unique:users',
'password' => 'required',
'companyName' => 'required',
'name' => 'required',
'country' => 'required|numeric'
];
}
}
My errors are coming back automatically, which appear to be the messagebag object serialised to JSON
{"email":["The email has already been taken."]}{"email":["The email has already been taken."]}
Somewhere in there I need to catch the Exception inside the main Controller, but I've used the Custom Request Class to clean up my controller a bit, how would I do that? Note the Exception already caught in this controller, which doesn't seem to pickup whatever is thrown behind the scenes in the custom request.
any pointers? do I need to move validation back to the controller? or is there a cleaner way to do this?
You can override the response method in CreateUserRequest to customize the response:
public function response(array $errors)
{
return parent::response($errors);
}
I'm making a REST API that should validate data entry from the user, to achieve that, I made a Request class that has the rules function that it should do the validations.
Request class
class StoreUpdateQuestionRequest extends Request {
public function authorize() {
return true;
}
public function rules() {
$method = $this->method();
$rules = [
'question' => 'required|min:10|max:140',
'active' => 'boolean',
];
return $method !== 'GET' || $method !== 'DELETE' ? $rules : [];
}
}
So, in the controller, when I try to run an endpoint which it fires the validations, it does work, it fails when it's has to, but it doesn't show me the errors as I expect, even though I defined the error messages in the messages function contained in the Request class, instead of showing me that errors, it redirects me to a location. Which sometimes is the result of a request I made before or it runs the / route, weird.
Controller function
public function store(StoreUpdateQuestionRequest $request) {
$question = new Question;
$question->question = $request->question;
$question->active = $request->active;
if($question->save()) {
$result = [
'message' => 'A question has been added!',
'question' => $question,
];
return response()->json($result, 201);
}
}
Any ideas? Thanks in advance!
In order to make this work, you have to add an extra header to your request:
Accept: application/json
That did the trick.
You can use controller based validation as described in documentation https://laravel.com/docs/5.2/validation#manually-creating-validators
public function store(Request $request) {
$validator = Validator::make($request->all(), [
'question' => 'required|min:10|max:140',
'active' => 'boolean',
]);
if ($validator->fails()) {
return response()->json($validator->errors());
}
//other
}