Set custom validation message for field in laravel5 form validation? - php

I want to set custom filed name in laravel5 form validation error messages.
my form validation request class is,
class PasswordRequest extends Request {
protected $rules = [
'old' => ['required'],
'new' => ['required','same:cnew'],
'cnew' => ['required']
];
/**
* 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 $this->rules;
}
}
Here when old,new and cnew emty, Error message will be like following,
The old field is required.
The new field is required.
The cnew field is required.
I want to display like following instead of above message,
Old password field is required
New password field is required
Confirmation password field is required.
How it is possible in laravel5 Form Request Validation method?

Option 1:
You can define your custom attributes in resources/lang/en/validation.php under Custom Validation Attributes 'attributes' => [], like so:
/*
|--------------------------------------------------------------------------
| Custom Validation Attributes
|--------------------------------------------------------------------------
|
| The following language lines are used to swap attribute place-holders
| with something more reader friendly such as E-Mail Address instead
| of "email". This simply helps us make messages a little cleaner.
|
*/
'attributes' => [
'old' =>'Old Paaword',
'new' =>'New password',
'cnew' =>'Confirmation password'
]

Related

How can I bypass a FormRequest validation in Laravel to store a user_id?

I'm building an API and I need to store a Customer. When the customer is stored, automatically, a User is created. The User created belongs to a Customer, and a Customer needs to store in his database the user_id previously created.
I have the following code where I use the FormRequest to store a new Customer. I use a DB Transaction to ensure the safeness of the operation. After I store the User, I use his id to associate to the field user_id in the Customer request.
public function store(StoreCustomerRequest $request)
{
/* --- DB Transaction -> Create User + Customer --- */
DB::transaction(function () use ($request) {
// -> Creates User
$create_user = (new UserController)->store($request);
// -> Creates Customer
$request->merge(['user_id' => $create_user->id]);
$customer = Customer::create($request->validated());
return new CustomerResource($customer);
});
}
The StoreCustomerRequest has the following rules.
public function rules()
{
return [
'user_id' => 'required|integer|exists:users,id',
'phone' => 'required|min:0|max:20',
'points' => 'required|min:0',
'nif' => 'nullable|digits:9',
'default_payment_type' => 'nullable|in:VISA,PAYPAL,MBWAY',
'default_payment_reference' => 'nullable',
'custom' => 'nullable'
];
}
When I try to store a new Customer, the field user_id goes null (because there is no user to associate with). Therefore, there is an error saying "The user id field is required.".
The question is: How can I bypass this validation and store the customer with the user_id previously created?
I have already tried to change the rules in the StoreCustomerRequest and make the user_id nullable, but when I try to store it, it says that the user cannot be null.
There is a rule in laravel called sometimes which only validates if a field is present. You can use that in the rules like so.
public function rules()
{
return [
'user_id' => 'sometimes|integer|exists:users,id'
];
}

When validating data in Laravel 5.5, Update returns "unknown column in field list" error where Create does not

Laravel 5.5 introduces a new streamlined request validation. The idea being that:
$validData = $request->validate($rules)
will return only those fields that are present in the $rules. This is beneficial so that one can then simply User::create($validData) or User::update($validData).
However, I noticed that when I have additional data, which I do validate, but that doesn't exist in the model's (this case User) table, the create method inserts the record, but that the update method returns this error:
Column not found: 1054 Unknown column 'column_name' in 'field list'
I can of course write the relevant field lists out, or use other workaround, but I wonder why are the two methods are behaving differently?
e.g. passing
array:4 [▼
"first_name" => "Pedro"
"last_name" => "Taco"
"email" => "taco#example.org"
"operators" => array:1 [▼
0 => "1"
]
]
to User::create() inserts the record. Passing the same to User::update() returns an error.
User has $fillable = 'first_name', 'last_name', 'email'
I believe they behave the same but in update method you have some extra fields that are not in table in database, so you should verify what exactly you send and what exactly you validate to make sure there are no additional fields in $validData when you are updating user.
If you think that's not the case, please show us exactly how the validation looks like for creating and updating user.
If you want to update specific data use where
User::where('id',1)->update($validData);
If you want to update all rows try something like this
User::where('id','!=',-1)->update($validData);
OR
User::query()->update($validData);
If you are trying to use validations, you can decouple the code even further using Request validations.
Here you have a full example of applying Request validations and extracting just the necessary data to store (or update) objects:
1. Generation the request:
php artisan make:request CreateUserRequest
2. Custom the validation rules:
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
// you specify here a previous condition before access to the method
// can be Auth::check() for example
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
// put here your validation rules like:
'first_name' => 'required|string|max:100',
];
}
3. Modify the method in your controller:
public function store(CreateUserRequest $request)
{
// getting all the attributes
$data = $request->only('first_name', 'last_name', 'other_attribute..');
// creating the object
$user = new User;
// adding data
$user->fill($data);
// saving in database
$user->save();
return response()->json([
"message" => "The user has been created.",
"data" => $user,
], 201);
}
* Notice that the $request used as an argument is of type CreateUserRequest, so this indicates to Laravel wath rules to apply.
We have also only pull the data that we want to store (check the $request->only part), that seemed to be the root of your problem.

yii2 user-defined validation of mobile number

i am new to Yii2. I want to validate mobile number by custom validation function. How can i validate mobile no in Yii2 and how can i use user-defined rule to yii2 and How can we add error message to any attribute in yii2 after form post? Thanks in advance
you need to edit your model. Lets say you have the following model:
class User extends ActiveRecord implements IdentityInterface
{
...
/**
* #inheritdoc
*/
public function rules()
{
return [
[['email', 'password', 'id'], 'required'],
[['email', 'username'], 'unique'],
['mobile', 'customValidation'] //<----this will be your custom validation
}
public function customValidation(){
//perform your validation here
if(/*has error*/){
$this->addError("mobile","Your mobile number is not valid.");
}
}
}
the addError method's first parameter is the atribute you want to add the error to and the second parameter is the message you want to show.
Hope this helps ;)
Maybe this could help anyone.
Use pattern match in Yii2 and validate your input field.
It's going to check and return alert message if number has less/more than 10 digits.
['mobile', 'match', 'pattern'=>"/^[0-9]{3}[0-9]{3}[0-9]{2}[0-9]{2}$/",'message'=> 'Not Correct Format - mobile number should have 10 digits.'],

Modifing the Auth registration system in Laravel 5.2 to include hidden form fields

every one.
I'm currently having an issue modifying the Auth registration system in Laravel 5.2. What I am trying to do, is have two separate loging system for regular users and admins. I added a new field into the database for the users called admin, and set the default to 0, or false. Using the registration page that Laravel's auth system uses, I added a hidden input and set the value to 1. This page will obviously be used to log in the admins so that they can enter the admin area.
When I submit the form, the admin field is simply set to the default value, which is not what I want for this portion of the site. Once the user clicks submit on this page, I want his information to get sent to the database the the admin value of 1. Is there any way of doing this?
Here is what I have done so far to customize the auth registration system.
I removed the name field and added a firstname and lastname field so that the users can enter both of these value in separate text inputs. I updated the User model to include these fields in the $fillable array and updated the AuthControllers validate method so that these fields could be validated.
Here is the code for each
Here is the User.php model file
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname', 'lastname', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token', 'admin',
];
}
and here os the AuthContoller file
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'admin' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'firstname' => $data['firstname'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'admin' => $data['admin'],
]);
}
}
As you can see, I also added the admin field in the User.php model file hoping that that would auto fill automatically.
If anyone can tell me how this could be done, that would be great. But as you can see this isn't really a practical solution for an actual website, but its more about learning the ins-and-outs of Laravel and learning how to customize the heck out of it. As I began to write this question out, it seemed to me, that I could easily just use the registration for any user, then allow an upper level admin to set the value of the admin field to true so that the user could venture into the admin sections of the application. Of course, will a system like this, there would be no need to have two separate log in screens, but like I said, I'm just learning.
I also plan on adding roles, similar to word presses for the various level's of admins, that would control things such as creating, editing, and publishing content such as posts. but for now, I'm just working on this system as it is.
Thanks for any help and comments about this topic.
First of all, as you have mentioned this is not at all a practical example, it is actually built on major security holes, so my answer here is to demonstrate the Laravel capabilities purely, without digging into the given example validity.
Second, no need to add a hidden field in the form, for the Admin status, you can set that value before saving the User Model:
$user = User($request->all());
$user->admin = 1;
$user->save()
In general to make something fill automatically. you need to specify that in the model
class User extends Model
{
protected $fillable = ['first_name', 'lastname', 'email', 'password', 'admin']);
}
If you are going to implement a role-based system there is no need to add 'admin' in the User model.
This is the short version of what I did
Permission model
- ID
- name
- display_name
- description
Role model
- ID
- name
- display_name
- description
- power
(Let's say both roles Manager and Admin can delete users,
the manager has 50 power and the admin has 90 power.
The manager is not able to delete the admin, but the admin can delete the manager.)
User model
- ID
- fname
- lname
- username
- email
- password
permission_role table
- permission_id
- role_id
$table->primary(['permission_id', 'role_id'])
role_user table
- role_id
- user_id
$table->primary(['role_id', 'user_id'])
With this setup your users can have multiple roles, and 1 permission can be in all roles.
I too made a separate login page for admins and other types of users.
To do this I use different routes
Route::get('/[secure_string]/auth', 'AuthController#getNormalLogin')->name('UserLogin');
Route::post('/[secure_string]/auth', 'AuthController#postNormalLogin');
Route::get('/[secure_string]/auth/strong', 'AuthController#getAdminLogin')->name('AdminLogin');
Route::post('/[secure_string]/auth/strong', 'AuthController#postAdminLogin');
(The secure string is placed in a config file,
anyone can guess /dashboard will get you to the CMS)
Both those methods will return the same view, but with a different action attribute on the form.
public function getNormalLogin() {
return view('login_form')->with(['action' => route('UserLogin')]);
}
public function getAdminLogin() {
return view('login_form')->with(['action' => route('AdminLogin')]);
}
My form looks like
<form method='post' action='{{ $action }}'>
// input fields and submit button
</form>
My post methods
public function validateForm($request) {
// validate input
}
public function fetchUser($username) {
return User::where('username', $username)->first();
public function postNormalLogin(Request $request) {
$this->validateForm($request);
$user = $this->fetchUser($request->get('username');
// see if the user has the admin role assigned (recommend writing a $user->hasRole($role) method)
if ($user->hasRole('admin')) {
// if so reject the login request
} else {
// continue with login
}
}
public function postAdminLogin(Request $request) {
$this->validateForm($request);
$user = $this->fetchUser($request->get('username');
// see if the user has the admin role assigned (recommend writing a $user->hasRole($role) method)
if ($user->hasRole('admin')) {
// continue with login
} else {
// if so reject the login request
}
}

How to validate input field against the database in Yii 2.0?

Suppose I have a field name id and I want the user to enter some integer in the id field but at the same time I want to check that id against the database whether it exists or not. If it exists then it should show some error.
Is there a function to achieve this in Yii 2.0?
If this is from a model, you can have a unique rule to it in the validation rules.
In your model, you have a rules() function:
/**
* #return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('name', 'required'),
array('some_id', 'unique'),
);
}

Categories