Here is my request class on which i want to pass custom messages for form requests.
I want to pass custom validation messages according to my custom rules.
<?php
namespace App\Http\Requests\Authenticate;
use App\Http\Requests\Request;
class AuthRequest 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()
{
// I want to return custom messages from here
return [
"email" => "required|email|exists:user,email",
'password' => 'required',
];
}
}
Any help appreciated. Thank you very much in advance.
Here is your answer. Add an extra function to pass messages.
public function messages()
{
return [
"required" => "The :attribute field is required.",
'email' => 'The :attribute should be valid email.',
'exists' => 'The :attribute already exists.'
];
}
Related
I have a form field and I want to validate if the entered value is a valid url OR a IP Address.
I have created a custom form request validation to validate the url (the available url validation from laravel was not enough) and that works fine.
But how can I change my Validation to check if it is an valid url or valid ip? It should only fail if both validation fails.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CheckDomain extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
*
* Manipulate Input Domain before Validation
*
*/
protected function prepareForValidation()
{
// Remove HTTP - HTTPS
$this->domain = str_replace([
'http://', 'https://'
], '', $this->domain);
$this->domain = strtok($this->domain, '/'); // Remove Slashes
$this->domain = strtolower($this->domain); // Make Lowercase
// Bring Together
$this->merge([
'domain' => $this->domain
]);
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'domain' => [
'required', 'regex:^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$^'
]
];
}
}
You can use this regex
^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?|^((http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$
And your code finally should be like:
public function rules()
{
return [
'domain' => ['required', 'regex:^(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?|^((http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$']
];
}
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')]
];
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
I've been struggling with laravel 5.2 login function messages. I've override the default sendFailedLoginResponse function in AuthController which works for failed attempts.
But I need to override the validate function response as well which I could not figure out how to do that. Also I do not want to override the default login functionality in the AuthContrller and want to stick with the same login function.
The reason for overriding the validate function is that am making an angular app and want the response in json format with some custom keys.
Currently default login function in Illuminate\Foundation\Auth\AuthenticateUsers.php
public function login(Request $request)
{
$this->validate($request, [
$this->loginUsername() => 'required', 'password' => 'required',
]);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
I want the response something like in the below sendFailedResponse function in AuthController
/**
* Get failed request response
*
* #param null
* #return null
*/
public function sendFailedLoginResponse()
{
return response()->json( [ 'status' => false, 'message' => $this->getFailedLoginMessage() ]);
}
Thanks
I don't know anything about Angular and handling json on laravel but I had similar problem while creating custom error message for postLogin function. take a look at this code, perhaps you could do something within form request.
This is my AuthController.php
use App\Http\Requests\LoginFormRequest;
/**
* Handle a login request to the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function postLogin(LoginFormRequest $request)
{
return $this->login($request);
}
Try using form request on the function postLogin
class LoginFormRequest 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 [
'email' => 'required|email',
'password' => 'required|min:6',
];
}
public function messages()
{
return [
'required' => 'Your :attribute is required.',
'min' => ':attribute must be at least :min characters in length.',
'email' => 'Please type valid email address.',
];
}
}
I came up with the solution by implementing JWT for authentication which I could think of is the best solution with Client side.