Customize Validation Messages in Laravel Requests - laravel

How do i customize my Validation Messages in My REQUESTS FILE?
how do i add messages next to the rules?
What i want is to put customized messages just like the common validation. Is it possible? to do just the normal way of validation in the Requests?
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class ArticleRequest 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|min:5',
'content' =>'required',
'user_id' => 'required|numeric',
'category_id' => 'required|numeric',
'published_at' => 'required|date'
];
}
}

You can define a messages() method with validation rules for that form request only:
class StoreArticleRequest extends Request
{
//
public function messages()
{
return [
'title.required' => 'The title is required.',
'category_id.numeric' => 'Invalid category value.',
];
}
}
It takes the form of the field name and the rule name, with a dot in between, i.e. field.rule.

You may customize the error messages used by the form request by
overriding the messages method. This method should return an array of
attribute / rule pairs and their corresponding error messages:
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}
https://laravel.com/docs/5.3/validation#customizing-the-error-messages

I use this solution to translate the field labels:
...
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'title' => 'required|min:5',
'content' =>'required',
'user_id' => 'required|numeric',
'category_id' => 'required|numeric',
'published_at' => 'required|date'
];
}
/**
* Get the validation attributes that apply to the request.
*
* #return array
*/
public function attributes()
{
return [
'title' => __('app.title'),
'content' => __('app.content'),
'user_id' => __('app.user'),
'category_id' => __('app.category'),
'published_at' => __('app.published_at')
];
}

Related

How to validate email in custom rule

I use Laravel.
I use the same field for username and email. Additionally the user has to choose, if the input is an username or an email.
If the type is email, i like to add the email validation. If it's username, there is no email validation needed.
I tried to create a custom rule with the if function. But how can i then validate the email?
class StoreUserRequest extends FormRequest
{
public function rules()
{
return [
'first_name' => 'required',
'last_name' => 'required',
'password' => 'required',
'email' => ['required', new ValidateEmailRule()]
];
}
public function authorize()
{
return true;
}
}
class ValidateEmailRule implements Rule
{
/**
* Create a new rule instance.
*
* #return void
*/
public function __construct()
{
//
}
/**
* Determine if the validation rule passes.
*
* #param string $attribute
* #param mixed $value
* #return bool
*/
public function passes($attribute, $value)
{
if (request()->is_email) {
//validate email ---here i need help to get the right code---
}
return true;
}
/**
* Get the validation error message.
*
* #return string
*/
public function message()
{
return 'The validation error message.';
}
}
Can't you just use 'email' => 'required_if:is_email:1?
EDIT:
$rules = [
'first_name' => 'required',
'last_name' => 'required',
'password' => 'required',
];
if ($this->is_email) {
$rules['email'] = 'email';
}
return $rules;

How do I show custom error messages with Laravel form requests?

I am new to Laravel, and have made a UserRequest class that handles validating incoming sign up requests. This is what I have inside it:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'firstname' => 'required|string',
'lastname' => 'required|string',
'email' => 'required|email',
'password' => 'required|string|min:6',
];
}
/**
* Custom message for validation
*
* #return array
*/
public function messages()
{
return [
'firstname.required' => 'First name is required!',
'lastname.required' => 'Last name is required!',
'email.required' => 'Email is required!',
'password.required' => 'Password is required!'
];
}
My question is do these error messages automatically show if the user doesn't enter a field, or is there anything else I need to do, ie in my controller?
Thanks!
you must include the UserRequest in your controller e.g.
use App\Http\Requests\UserRequest;
And make sure you define your incoming request as a UserRequest (and not a regular Laravel Request) e.g.
public function update(UserRequest $request)
The validation should then be performed automatically.

Laravel unique validation in request with other fields WITHIN that request?

`I want to make a unique validaiton against the following fields
email - from Users table
shop_id - from Staff table
staff_roles sent via an array of strings e.g ["shop_manager", "shop_cleaner"]. If any email/shop_id/role exists already the request should not be valid - from StaffRoles table
If a combination of those fields exists in the DB, the request should be considered invalid.
Here's my AddStaffRequest:
public function rules()
{
return [
'shop_id' => ['required', 'uuid'],
'email' => ['required', 'email'],
'staff_roles' => ['array'],
'staff_roles.*' => ['string'],
];
}
Is there a simple solution for this?
You can define a "after" validator:
/**
* Configure the validator instance.
*
* #param \Illuminate\Validation\Validator $validator
* #return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
$attributes = $validator->attributes();
if (StaffRoles::where([
['email', $attributes['email']],
['shop_id', $attributes['shop_id']],
['role', $attributes['role']]])->count() != 0)
{
$validator->errors()->add('constraint_name', 'the combinations already exists');
}
});
}
What about assembling a query which would validate the request, given the fact that this is a tad more complex logic?
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::exists('staff')->where(function ($query) {
$query->where('account_id', 1);
}),
],
]);

How response message() on Request

i'm need response json messages()
class StoryRequest 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|min:3|max:255|unique:stories',
'categories' => 'required',
'image' => 'mimes:jpeg,bmp,png, jpg',
];
}
public function messages()
{
return response()->json([
'image.mimes' => 'only .jpg, .png, .jpeg',
'name.required' => 'please name',
'name.min' => 'min 3',
'name.max' => 'max 255',
'name.unique' => 'name unique',
'categories.required' => 'please choose categories'
]);
}
}
Try this return redirect('/home')->with('success', 'Password Updated Successfully');

Controller method not found laravel

Hello i have been using implicit controllers for a hile now but today i am having an issue i just cannot understand, i have the following in my Route.php:
/**
* Purchase
*/
Route::controllers([
'purchase' => 'PurchaseController'
]);
and in my controller i have created this method:
public function postNsano(NsanoRequest $request)
{
$data = [
'code' => $request->code,
'msg' => $request->msg,
'reference' => $request->referencecode
];
if ($request->code == "00")
{
Session::put('nsano_callback_post_data', $data);
return [
'code' => '00',
'msg' => 'success'
];
}
else
{
return [
'code' => '01',
'msg' => 'rollback'
];
}
}
Now for some reason when i try and post to this URL:
sample.com/purchase/nsano
I get this error: "Controller Method Not Found"
Which is odd for me because i can see the method right there.
I took out the $request and just used Input::get() instead and now it works can someone please explain this to me?
This is my request:
class NsanoRequest 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 [
'code' => 'required',
'msg' => 'required',
'reference' => 'required'
];
}
}
Implicit controller routing needs the HTTP verb in the method name:
public function postNsano(NsanoRequest $request)
{
//
}
Your request validates do not correct so it jumps to an url to prompt error but not found.
If you add some parameters like this and than OK.

Resources