I have a custom "base" validator
class BaseUserRequest extends FormRequest
{
...
public function messages()
{
return [
'password.min' => 'Custom error',
];
}
}
And other validator extends "base" class
class RegisterUserRequest extends BaseUserRequest
{
...
public function messages()
{
return parent::messages();
}
}
When I try to trigger password:min error on form, which uses RegisterUserRequest, I get default message instead "Custom error" message. What's wrong with my RegisterUserRequest class?
If I use BaseUserRequest, I get my "Custom error" message. Something is wrong with class inheritance.
UPDATE (QUESTION SOLVED): I forgot to register rules on validation
not
return Validator::make($data, (new RegisterUserRequest())->rules());
but
return Validator::make($data, (new RegisterUserRequest())->rules(), (new RegisterUserRequest())->messages());
try this way
php artisan make:request BaseUserRequest
// app/Http/Requests/BaseUserRequest.php
public function messages()
{
return [
'password.min' => 'Custom error',
];
}
// app/Http/Controllers/UserController.php
use App\Http\Requests\BaseUserRequest;
public function register(BaseUserRequest $request)
{
// register code here
}
Related
I am using Laravel v9.2.1 + Laravel Sanctum v2.14.1
I got a route
DELETE /api/v1/auth/tokens/{token}
for example (the token is an uuid)
DELETE http://example.com/api/v1/auth/tokens/5fcfa274-81d8-4e9f-8feb-207db77531af
And I am sure it works as expected via php artisan route:list
Before handling by the Controller, it should be validated by a FormRequest
app/Http/Controllers/V1/Auth/TokensController.php
namespace App\Http\Controllers\V1\Auth;
use App\Http\Requests\V1\Auth\Tokens\{
DestroyRequest,
};
class TokensController extends Controller
{
public function destroy(DestroyRequest $request) {
$request->user()->tokens()->where('id', $request->token)->first()->delete();
return response()->noContent();
}
}
app/Http/Requests/V1/Auth/Tokens/DestroyRequest.php
class DestroyRequest extends FormRequest
{
public function rules()
{
return [
'token' => [
'required',
'string',
'regex:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
Rule::exists('personal_access_tokens')->where(function ($query) {
return $query->where('tokenable_id', $this->user()->id);
}),
]
];
}
}
But what I only got is The token field is required
I had already pass the token, why the 'required' rule still working?
What I tried
Only if I pass the token parameter like below, it will work
DELETE /api/auth/tokens/something?token=test_regex_is_working
I try to dd($this->token) in app/Http/Requests/V1/Auth/Tokens/DestroyRequest.php, it works as expected.
i might try going about it differently as the token isn't really user input
In the routes file:
Route::delete('/api/v1/auth/tokens/{token}', [TokensController::class, 'destroy'])->whereUuid('token');
In the FormRequest something maybe like this:
public function authorize()
{
return DB::table('personal_access_tokens')
->where('tokenable_id', Auth::id())
->where('token', $this->route('token'))
->exists()
}
You might need to add the following in the FormRequest class:
protected function prepareForValidation()
{
$this->merge(['token' => $this->route('token')]);
}
I believe URL parameters are not included in the request directly.
With the help of both #RawSlugs and #Aaron T, thank them a lot!
app/Http/Requests/V1/Auth/Tokens/DestroyRequest.php
protected function prepareForValidation() {
$this->merge(['token' => $this->route('token')]);
}
public function authorize() {
return $this->user()->tokens()->where('id', $this->token)->exists();
}
// But since the authorize() will validate the request before rules(), this will be useless
public function rules() {
return [
'token' => [
'required',
'string',
'regex:/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
]
];
}
I'm using Laravel Sanctum.
Below is my code;
FruitRequest.php
class FruitRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required|alpha',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
];
}
public function messages()
{
return ['name.required' => response("Name should be mandatory", 404),
'name.alpha' => response("Name should be contains only letters", 404),
'image.required' => response("Foto should be mandatory", 404),
'image.mimes' => response('Foto should be jpeg,png,jpg,gif,svg', 404),
'image.max' => response('Foto size should be blow 2 MB', 404),
];
}
}
FruitController.php
use App\Http\Controllers\Controller;
use App\Http\Requests\FruitRequest;
class FruitController extends Controller
{
public function store(FruitRequest $request)
{
echo $request->input('name');
//above line gives nothing to me
}
}
If I use extends Request instead of extends FruitRequest then this gives me value which is passed by user in postman. I don't know why this custom Request class not working.I attached screenshot. Please help....
extend your request class with FormRequest
use Illuminate\Foundation\Http\FormRequest;
class FruitRequest extends FormRequest
for more details visit official doc of laravel: https://laravel.com/docs/7.x/validation#creating-form-requests
long time not using postman, i'm testing with my code
I'm using FormRequest like this:
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
class YourRequest extends FormRequest
{
//this function called if Validator::make()->fails();
//here where you can modifying your message
protected function failedValidation(Validator $validator)
{
//note this only for API, for formData use \Illuminate\Validation\ValidationException($validator)
throw new HttpResponseException(response()->json($validator->errors()->all(), 422));
//this will get parameter attribute set from FormRequest
//attributes() along with the error message,
//or $validator->errors()->all() to get messages only like my screenshot
//or modify message with your logic
}
public function authorize() { return true; }
public function rules() { return []; }
public function attributes() { return []; }
public function messages() { return []; }
}
in controller :
use YourRequest;
public function store(YourRequest $req)
{
return response($req->all())->setStatusCode(200);
}
in your FormRequest replace response(), just text:
public function messages()
{
return ['name.required' => "Name should be mandatory"],
}
2nd, validation alpha only accepts alphabet, which your name is numeric,
result from my code(i use default validator message which in array of messages) :
I have a very simple Rule method in request class like below.
public function rules()
{
return [
'Subject' => 'required|max:50',
'Description' => 'required|max:500',
'DepartmentID' => 'required|integer|min:1',
'PriorityID' => 'required|integer|min:1'
];
}
Inside Controller Action method, below is the code.
private function SaveChanges(\App\Http\Requests\TicketRequest $request) {
$v = \Validator::make($request->all(), [
]);
$DepartmentAdmins = $this->getDepartmentAdmins();
//Check if department admin missing then no need to add the record
if($DepartmentAdmins == null || count($DepartmentAdmins) == 0) {
$v->errors()->add('MissingAdmins', 'Department admin missing.');
return redirect()->back()->withErrors($v->errors());
}
}
Question:
As we can see in the rule method there are 4 form fields. Is there any way to shift the check for Department Admin existence from Controller Action method to request class?
Laravel's Request has after hook that can be run after normal validation completes. This is how you can use it in your case:
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\Models\Property;
use Illuminate\Validation\Validator;
class SomeRequest extends Request
{
/**
* Get the validator instance for the request.
*
* #return Validator
*/
protected function getValidatorInstance()
{
$instance = parent::getValidatorInstance();
$instance->after(function ($validator) {
$this->validateDepartmentAdmins($validator);
});
return $instance;
}
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'Subject' => 'required|max:50',
'Description' => 'required|max:500',
'DepartmentID' => 'required|integer|min:1',
'PriorityID' => 'required|integer|min:1'
];
}
/**
* #param Validator $validator
*/
public function validateDepartmentAdmins(Validator $validator)
{
$DepartmentAdmins = $this->getDepartmentAdmins();
//Check if department admin missing then no need to add the record
if($DepartmentAdmins == null || count($DepartmentAdmins) == 0) {
$validator->errors()->add('MissingAdmins', 'Department admin missing.');
}
}
That way you won't have to do any validation in your SaveChanges controller method.
This code is used in Laravel 5.1, but I believe it will work the same in 5.2.
The Form Request Class basically has two methods. "authorize" and "rules". the best way to shift the check for Department Admin existense is to add your own custom validator(for example named "adminCountValidator") and implement your logic for checking the number of administrators there. Then use yoir newly defined validator in "rules" method like this:
public function rules()
{
return [
'Subject' => 'required|max:50',
'Description' => 'required|max:500',
'DepartmentID' => 'required|integer|min:1|adminCountValidator',
'PriorityID' => 'required|integer|min:1'
];
}
if you define a custome validation rule, you can also define the associated error message and your controller action will be much more cleaner. here is the link for defining your own custom validator
custom-validation-rules
here is a sample code for adding a custom validator within a service provider
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('adminCountValidator', function($attribute, $value, $parameters, $validator) {
/*
implement your getDepartmentAdmins()
function here and return true or false
*/
});
}
I am creating Rest Full Api for mobile application, I am validating request it redirects me to the login page with errors.
Here is my ApiController (I have created for all api):
use App\User as UserModel;
use App\Fb_friend as FbFriendsModel;
use App\Http\Requests\UserRequest;
class ApiController extends Controller
{
/**
* Create a new movie model instance.
*
* #return void
*/
public function __construct(UserModel $user, FbFriendsModel $fb_friends){
$this->user = $user;
$this->fb_friends = $fb_friends;
}
public function createUser (UserRequest $request) {
// some code here
}
Route:
Route::post('createUser', ['as' => 'createUser', 'uses' => 'ApiController#createUser']);
UserRequest.php:
public function rules()
{
return [
'fb_id' => 'required|unique:users',
'username' => 'required|unique:users',
'email' => 'required|unique:users',
'image' => 'required',
'device_id' => 'required',
'status' => 'required',
];
}
I have override a function Request.php for error formatting:
abstract class Request extends FormRequest
{
protected function formatErrors(Validator $validator)
{
return [$validator->messages()->toJson()];
}
}
When I try to call service via postman, it returns me error in json format but it also print the login page, I m not getting why?
If you are using Postman for testing API's, it is not necessary to override the response() in Request class, One can follow the following steps,
make return type in authorize() in your custom Request as true,
public function authorize()
{
//make it true
return true;
}
Go to headers section in your Postman and define Accept type,
Accept:application/json
Now hit the endpoint of your API and bam..working fine for me.
It has been done by override the response method in app/Http/Requests/Request.php
public function response(array $errors) {
if ($this->ajax() || $this->wantsJson() || Request::isJson()) {
$newError = [];
$newError['result'] = false;
$newError['errors'] = $errors;
// in the above three lines I have customize my errors array.
return new JsonResponse($newError, 422);
}
return $this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors);
}
We also need to use JsonResponse class at the top
use Illuminate\Http\JsonResponse;
Source: https://laracasts.com/discuss/channels/general-discussion/laravel-5-validation-formrequest
Can I ask what have I done wrong in my LoginRequest.php where I've set a condition to redirect to a custom login page if there is any sort of error in the login process? I have my codes as below:
<?php namespace App\Http\Requests;
use App\Http\Requests\Request;
class LoginRequest 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 [
'login_email' => 'required',
'login_password' => 'required'
];
}
public function messages()
{
return [
'login_email.required' => 'Email cannot be blank',
'login_password.required' => 'Password cannot be blank'
];
}
public function redirect()
{
return redirect()->route('login');
}
}
The code is supposed to redirect users who login from a nav bar login form to the main login page, if there are any errors, but it doesn't seem to redirect.
if you want to redirect to a specific url, then use protected $redirect
class LoginRequest extends Request
{
protected $redirect = "/login#form1";
// ...
}
or if you want to redirect to a named route, then use $redirectRoute
class LoginRequest extends Request
{
protected $redirectRoute = "session.login";
// ...
}
If you do not want to use the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance: Refer to Laravel Validation
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
Found a solutions. All I need to do is to override the initial response from
FormRequest.php
like such and it works like a charm.
public function response(array $errors)
{
// Optionally, send a custom response on authorize failure
// (default is to just redirect to initial page with errors)
//
// Can return a response, a view, a redirect, or whatever else
if ($this->ajax() || $this->wantsJson())
{
return new JsonResponse($errors, 422);
}
return $this->redirector->to('login')
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
}
This works in Lara 7
Add an anchor to jump to the comment form if validation fails
protected function getRedirectUrl()
{
return parent::getRedirectUrl() . '#comment-form';
}
If you are using the validate() method on the Controller
$this->validate($request, $rules);
then you can overwrite the buildFailedValidationResponse from the ValidatesRequests trait present on the base Controller you extend.
Something along this line:
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->expectsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->route('login');
}
Variations on this answer have already been offered, but overriding the getRedirectUrl() method in a custom request can enable you to define the route parameters, rather than just the name that the $redirectRoute property offers.