Combine validated date and non-validated data to store in laravel - php

Here i have two inputs field as name and age.
I wanna validate name but not age.
How can i send both value to store.
request()->validate([
'name' => 'required',
]);
//Here i wanna add 'age' along with 'name' in $request
//Then i must store.
Pastor::create($request->all());

The $request->all() already sends whatever is in your request. But if you like you can specifically pass request values to create method like this:
Pastor::create([
'name'=> $request->name,
'age' => $request->age
//any other fields
]);
I assume you have named your inputs like i have passed into create method and it should work.

use the Validator class Laravel has. lets say you have UserController
Use Validator;
Use App\User;
class UserController extends Controller
{
// Your Validator
protected function yourValidatorName(array $data)
{
$rules = ['name'=>'required'];
return Validator::make($data,$rules);;
}
// Your Main Function
public function yourFunctionName(Request $request)
{
$isValid = $this->yourValidatorName($request->all());
if(!isValid->fails())
{
// your code here (validation passed)
}
else
{
// your code here (validation failed)
}
}
}

You simply put a check on name field only
$this->validate($request,[
'name' => 'required|min:3|max:200',
],[
'name.required' => 'name is a required field.', // custom messages you can omit them
'name.min' => ' Name must be at least 3 characters.', // custom message for minimum characters
'name.max' => ' Name should not be greater than 200 characters.', // custom message for maximum characters
]);
Pastor::create($request->all());
Without custom messages
$this->validate($request,[
'name' => 'required|min:3|max:200',
]);
Pastor::create($request->all());

Related

Laravel Validation Request, how to handle validation on update?

First of all I love the way that validation is going through, can now easily use
public function authorize(Authenticator $auth)
{
return $auth->user()->hasRole('administrator');
}
hat's not the problem, I bump always into another problem... that is when you update an record, how to do things with the rules? If I need to update an email, I need the following string: 'email' => 'unique:users,email_address,10'. In this case it should look like:
public function rules()
{
return [
'email' => 'required|unique:users,id,?????',
'tags' => 'required'
];
}
It's more simple.
The Laravel documentation says "If your table uses a primary key column name other than id, you may specify it as the fourth parameter":
'email' => 'unique:users,email_address,'.$user->id.',user_id'
If for example, you want to verify if a username exists, but excluding current user ID:
// UpdateUserRequest.php
public function rules() {
//
return [
'username' => 'required|unique:users,username,' . $this->id . ',id',
];
}

Image validation in Edit form in laravel 5.2

I have a issue, Please take a look below.
I have a edit user profile section where we update user account, i want to check if no image exists in table & user too not provided image then we have to validate the image & show an error. if there is already a image exists in table then no image validation suppose to check. Everything works good except image validation.
i am using from request for validation. below is my validation rules in request file.
public function rules()
{
return [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'required|image',
'zip_code' =>'required|numeric|min:5',
];
}
I am using Laravel 5.2, Thanks in advance.
Finally i figure out the solution using help of #Amir. below is the complete solutions of this issue.
//add this in user model
public function notHavingImageInDb(){
return (empty($this->image))?true:false;
//return true;
}
//import the User model & Auth class in request class.
use App\User;
use Auth;
//add this in from request
public function rules()
{
$user = User::find(Auth::id());
$rules = [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'image',
'zip_code' =>'required|numeric|min:5',
];
if ($user->notHavingImageInDb()){
$rules['image'] = 'required|image';
}
return $rules;
}
Now all done.
In the above code we check if the column has some value or not in validation, if yes then model function return true, this make the if condition active in request class, else, if condition remain inactive. works like charm.
Thanks
take a look at Conditionally Adding Rules:
so something like:
$v->sometimes(['image'], 'required|image', function($input) use ($user) {
return $user->notHavingImageInDb();
});
you can also use plain logic like:
public function rules()
{
$roles = [
'user_type' =>'required',
'first_name' =>'required|max:100',
'last_name' =>'required|max:100',
'email' =>'required|email|max:100',
'image' =>'image',
'zip_code' =>'required|numeric|min:5',
];
if ($user->notHavingImageInDb())
$rules['image'] = 'required|image';
return $rules
}
You can create another request class and name it UserUpdateRequest with artisan
like
php artisan make:request UserUpdateRequest
in this request class you just have to remove 'required' it will be like that
'image' => 'image'
and set UserUpdateResuest as parameter to update method like
public function update(UserUpdateRequest $userUpdateRequest, $id){
//
}

Laravel 4 Form Validation should be unique on update form, but not if current

I am trying to validate an update user profile form, whereby the validation should check that the email doesn't exist already, but disregard if the users existing email remains.
However, this continues to return validation error message 'This email has already been taken'.
I'm really unsure where I'm going wrong. Otherwise, the update form works and updates perfectly.
HTML
{{ Form::text('email', Input::old('email', $user->email), array('id' => 'email', 'placeholder' => 'email', 'class' => 'form-control')) }}
Route
Route::post('users/edit/{user}', array('before' => 'admin', 'uses' => 'UserController#update'));
User Model
'email' => 'unique:users,email,{{{ $id }}}'
Your rule is written correctly in order to ignore a specific id, however, you'll need to update the value of {{{ $id }}} in your unique rule before attempting the validation.
I'm not necessarily a big fan of this method, but assuming your rules are a static attribute on the User object, you can create a static method that will hydrate and return the rules with the correct values.
class User extends Eloquent {
public static $rules = array(
'email' => 'unique:users,email,%1$s'
);
public static function getRules($id = 'NULL') {
$rules = self::$rules;
$rules['email'] = sprintf($rules['email'], $id);
return $rules;
}
}
You can accomplish this with the sometimes function of the validator
Something like:
$validator->sometimes('email', 'unique:users,email', function ($input) {
return $input->email == Input::get('email');
});
See http://laravel.com/docs/4.2/validation#conditionally-adding-rules for more info

how to validate form field in cakephp using model and controller

I have created a form which I need to validate using model and controller .Here is my form
index.ctp
<?php echo $this->Form->create('Contact',array('url'=>array('controller'=>'contacts','action'=>'add')));
echo $this->Form->text('name');
Model : Contact.php
class Contact extends AppModel
{
var $name = 'Contact';
var $useTable = false;
public $validate = array(
'name' => array(
'alphaNumeric' => array(
'rule' => 'alphaNumeric',
'required' => false,
'message' => 'Letters and numbers only'
),
'between' => array(
'rule' => array('between', 5, 15),
'message' => 'Between 5 to 15 characters'
)
)
);
}
Controller : ContactsController.php
public function add()
{
$this->Contact->validates();
$this->request->data['Country']['country_name']=$this->request->data['Contact']['country'];
$this->Country->saveall($this->request->data);
$this->redirect('/Contacts/index/');
}
I am trying to do the validation by googling but it seems difficult to me so if anyone could describe the process it would be a great help .My cakephp version is 2.3.8. I just need to validate this name field , as when I click in submit it will show this message in the form.
Your controller code should be like this
The process of validation in CakePHP is like
1) as you have defined validation rules in CakePHP model public `$validates = array();`
2) when ever you do a save on particular model directly or through any association
a callback method beforeValidate for that model gets called to validate the data which is being saved.
3) once the data is validated then beforeSave callback is called after this save method is called.
4) we can also validate the form input fields in controller using $this->Model->validates() but then while saving we have to disable the beforeValidate callback by doing
$this->Model->save($data,array('validate'=>false));
Otherwise you will end validating the same data twice
your controller code should be somewhat like this.
public function add() {
// here we are checking that the request is post method
if ($this->request->is('post')) {
$this->request->data['Country']['country_name']
= $this->request->data['Contact']['country'];
// here we are saving data
if ($this->Contact->saveAll($this->request->data)) {
//here we are setting a flash message for user
$this->Session->setFlash('your record has been added','success');
$this->redirect(array('controller'=>'contacts','action' => 'index'));
} else {
//here we are setting a flash message for user for error if input are not
//validated as expected
$this->Session->setFlash('sorry we could add your record','error');
}
}
}
For more information you can always refer to http://book.cakephp.org/2.0/en/models/callback-methods.html

Laravel validation service with unique fields

I'm using a validation service to validate user submitted form input (something along the lines of: http://laravel.io/bin/vrk).
Using this approach (validation service classes) to validate user submitted form data against a set of rules, how can I validate user submitted data when rules have a unique rule. For example, if a user has the username of John then when I try to update the model validation fails (because John exists as a username, even though it belongs to the current model).
To solve this in Laravel I can do something like 'username' => 'required|alpha_dash|unique:users,username'.$id. How should I modify my current code, in the link, to best accommodate this? Should I have separate validator classes depending on the scenario (for example, UserCreateValidator, UserUpdateValidator, etc). Or should I do something like create separate validation rules in UserValidator class and pass which rule I want as an argument to either the constructor or the passes() method when calling UserValidator?
I think you could do something like this
First update UserValidator rules like this.
class UserValidator extends Validator {
// Override parent class $rules
protected $rules = [
'default' => [
'username' => 'required|alpha_dash|unique:users',
'password' => 'required|between:6,16|confirmed',
'password_confirmation' => 'required|between:6,16'
],
'update' => [
'username' => null,
]
];
}
Then modify Validator's passes method like this
public function passes($rule = null) {
$rules = $this->rules['default'];
if ($rule && isset($this->rules[$rule])) {
$rules = array_merge($rules, $this->rules[$rule]);
}
$validator = \Validator::make($input, $rules);
if ($validator->fails()) {
$this->validator = $validator;
return false;
}
return true;
}
Then in your controller's PUT method, this will merge update rules to default rules
$rule = 'update';
// user has changed his username
if ($input['username'] !== $old_username) {
$rule = 'create'; // validate uniqueness
}
else {
unset($input['username']); // remove it, we don't validate it anymore since it's the same
}
$validator->passes($rule); // override 'default' rules with 'update' rules
You don't have to change your controller's POST method, it'll stay the same
$validator->passes(); // use 'default' rules
If I'm understanding right, you have issues updateng data because of primary key constraints on your model. What you need to do is to create 2 sets of rules, one for insert, and one for update.
Asuming you have a set of rules like this:
protected $rules = [
'id' => 'required|unique:users'
]
You should implement something like this:
protected $rules = [
'id' => 'required|unique|unique:users,id,' . $this->id
];
This should tell laravel to ignore the duplicate id in the table users for the specified id, in this case, the id for the current object.
You can read more about this on laravel's documentation at http://laravel.com/docs/validation
unique:table,column,except,idColumn
The field under validation must be unique on a given database table.
If the column option is not specified, the field name will be used.
Well, what are you doing on post?
Because this is what you should be doing:
$user = User::find($userId);
$user->username = $input['username'];
$user->email = $input['email'];
$user->save();
To update a record.
Or
$input = array('username' => 'w0rldart', 'email' => 'hahafu#dumbledore.com');
// Retrieve the user by the attributes, or create it if it doesn't exist,
// based on the data above, which can come from an Input::all();
$user = User::firstOrCreate($input);
... many possibilities. But you could also do:
$input = array_forget($input, 'username');
To comply with your case, by removing the username index from the input array.
This is all I call tell you, based on the information you gave us. If you want more, post the controller's put method.
Update:
Here's my version of your PUT method: http://laravel.io/bin/OaX
I really think that try catch syntax is useless, since it's obvious that a User model will always be there. But I still don't know what you're trying to update. Even though I can't test it right now, I don't think that updating should be giving that problem, and if it does, retrieve user by username/id then unset the username index in your input array, and update it according to your specifications.
A little modification in UserValidator class
class UserValidator extends Validator {
// Override parent class $rules
protected $rules = [
'username' => 'required|alpha_dash|unique:users',
'password' => 'required|between:6,16|confirmed',
'password_confirmation' => 'required|between:6,16'
];
// ADD THIS
public function __construct(Array $rules = array())
{
parent::__construct();
if(count($rules)){
foreach($rules as $k => $v) $this->rules[$k] = $v;
}
}
}
In your controller putUpdate method
$user = User::whereUsername($username)->firstOrFail();
$rules = ['username' => 'required|alpha_dash|unique:users,username,'. $user->id];
// Pass the rule to update the rule for username in this method
$validator = \Services\Validators\UserValidator(Input::all(), $rules);
Check the manual here.

Categories