Laravel 5 Validations - php

I want to validate my form fields using laravel 5.
Form field 1 -> User ID :
Form Field 2 -> Other Name :
Either of the form field is required.
i mean if user id is present other name should be blank and if other name is present user_id should be blank.
I am trying to use:
$validator = Validator::make(
[
'user_id ' => $user_id,
'user_name' => $user_name
], [
'user_id' => 'required_without:user_name',
'user_name' => 'required_without:user_id'
]);
if ($validator->fails()) {
return Utility::validation_err($validator);
}
While updating record even if user id is present it gives me error user id is required when other name is not present. also if i am filling out both it accepts both. It should accept one of both fields.
Any help will be appreciated.

You can use your own validation rule, for exmaple "only_one_id_name_required". It should be applied to both of fields. Next put extend Validator in App\Providers\AppServiceProvider
Validator::extendImplicit('only_one_id_name_required', function($attribute, $value, $parameters, $validator) {
return (request()->has('user_id') xor request()->has('user_name'));
});
Use extendImplicit() instead of extend() to cover empty fields request.

Related

Returning HTTP code to POST form in Laravel

I have a very simple view which contains a form. This form contains 2 select fields populated with data from the database.
Let's say the first select contains "Banana", "Apple", "Orange". The second one contains "Burger", "Pizza", "Hot Dog".
I'm submitting the form (POST) and saving the combination in a table of my database. Before actually saving, I'm checking if the combination doesn't already exist. I don't want to save "Banana - Burger" twice.
If the combination already exists I'm returning the following:
session(['error' => 'This combination already exists.']);
return redirect()->back()->withInput();
This brings me back to my form, and shows the error message in a popup.
How can I return the proper HTTP code (409 in this instance)?
You can make changes in your laravel validation for that. Replace your table name and field name in below example.
$data = $request->all();
$request->validate([
'fruits' => [
'required',
Rule::exists('fruits')->where(function ($query) {
$query->where('fruit_name', $data['fruit_name']);
}),
],
'foods' => [
'required',
Rule::exists('foods')->where(function ($query) {
$query->where('food_name', $data['food_name']);
})
]
]);
Hope this will help you.

Laravel 5.6: Skip validation step if field exists and isn't changed. If field IS changed it is Required - but not unique

I have situation where an admin edits an employee form: The first name, last name, and SSN are required on ADDING an employee. No problems there. Where I have an issue is when EDITING the form. I have no problem validating the SSN as it is a unique field.
'ssn_edit' => 'required|unique:employees,ssn,' . $id
But what I DO have an issue with is the non-unique fields. I don't know how to set the validation to skip by ID when the field is NOT unique. Here is the entire rules section of the FormRequest:
public function rules()
{
$id = $this->input('employee_id');
return [
'first_name' => 'required',
'last_name' => 'required',
'ssn_edit' => 'required|unique:employees,ssn,' . $id
];
}
Obviously - this throws the validation error on first_name and last_name regardless if the field is populated or not.
Any help some of you Laravel gurus can throw my way would be GREATLY appreciated!
There is so many tricks you can do to solve the problem. But I only got two ways..
The first is: Prevent to send your ssn_edit value when you want to edit the employee
example:
<input type="text" value="{{ isset($employee) ? $employee->ssn_edit : old('ssn_edit') }}" #isset($employee) disabled #endisset name="ssn_edit">
public function rules()
{
$id = $this->input('employee_id');
return [
'first_name' => 'required',
'last_name' => 'required',
'ssn_edit' => 'required|sometimes|unique:employees,ssn,' . $id
];
}
The second is: Check your method before validate the employee.. is it POST or PUT, if it's PUT don't add the unique rule in your validation.
Conclusion: The validation will work every time you call the validation, no matter if you edit or add new employee. #CMIIW
You mustn't have error with validating non-unique fields, probably you have wrong edit form, set value attribute to input like
<input type="text" value="{{ $employee->first_name }}" name="first_name">

Laravel 5.2 - validation - One of the fields is required

Take a scenario,
There are 2 fields available in the form.
1) input type file for manual upload.
2) input type = text to enter youtube video url.
is it possible using laravel built-in validations so that validation will be fired if user has left both fields empty!
I have gone through https://laravel.com/docs/5.3/validation but could not find what I wanted.
In your controller, you could do something like this:
$validator = Validator::make($request->all(), [
'link_upload' => 'required|etc|...',
]);
$validator2 = Validator::make($request->all(), [
'file_upload' => 'required|etc|...',
]);
if ($validator->fails() && $validator2->fails()) {
// return with errors
}
Try required-without-all validation rule. As given in documentation:
The field under validation must be present only when the all of the other specified fields are not present.
Assuming your fields name are url and file, your rule would be like below:
$rules = [
'url' => 'required_without_all:file',
'file' => 'required_without_all:url'
];
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are not present.
Try this,
In youre update method add this
$this->validate($request, [
'fileName'=>'required',
'urlName'=>'required'
]);
dont forget to set the fillable in your model
protected $fillable = ['fileName','urlName'];
Hope this helps

Laravel validate unique if id is the same

I have a table/model that contains multiple albums per user.
Is there a way to say that the column title should be unique, but only for the rows that have the same user_id?
Example: http://pastebin.com/8dvM4a1T
As you can see in the example, the user with the id of 2 has created 2 albums, with the same title. I don't want that to be allowed, that's why I'm wondering if there's a way to deny that with the validator from Laravel?
I tried this, but that did not work.
// Validator
$validator = Validator::make($input, [
'title' => 'required|min:1|max:255|unique:galleries,title,'. Auth::user() -> id .',user_id',
'description' => 'min:1|max:255'
]);
Any help appreciated, thanks.
Your code should be something like:
'title' => 'unique:galleries,title,NULL,id,user_id,'.Auth::user() -> id.'',
Or, you can write a custom rule
Reference here
The approach with the default unique rule does not work because the rule expects the column value to be passed as the third parameter, so in your case it would check if the title column is equal to the Auth::user()->id value which is not what you want.
You can create you own custom validation rule by adding the following code to the boot method of the App\Providers\AppServiceProvider class:
Validator::extend('unique_custom', function ($attribute, $value, $parameters)
{
// Get the parameters passed to the rule
list($table, $field, $field2, $field2Value) = $parameters;
// Check the table and return true only if there are no entries matching
// both the first field name and the user input value as well as
// the second field name and the second field value
return DB::table($table)->where($field, $value)->where($field2, $field2Value)->count() == 0;
});
Now you can use the unique_custom (or you can name it whatever you like) rule like so:
$validator = Validator::make($input, [
'title' => 'required|min:1|max:255|unique_custom:galleries,title,user_id,' . Auth::id(),
'description' => 'min:1|max:255'
]);
The rule expects the parameters to be the following:
the 1st parameter to be the table name, which in this case is galleries
the 2nd parameter to be the field name that is supposed to be unique and for which the value comes from the user input, which in this case is title
the 3rd parameter to be the second field name that will be added to the query conditions, which in this case is user_id
the 4th parameter to be the value of the field name passed as the third parameter
Also you can use Auth::id() since that is the short form of Auth::user()->id.
You can read more about Custom Validation rules in the Laravel Documentation.
Laravel 5.3 and above
use Illuminate\Validation\Rule;
'email' => Rule::unique('galleries')->where(function ($query) {
$query->where('user_id', Auth::id());
})
Laravel 9
use Illuminate\Validation\Rule;
Rule::unique('galleries')->where(fn ($query) => $query->where('user_id', Auth::id()))

Laravel rule for unique excluding blank or null

I have a user model that needs to have unique email addresses but I also want to allow them to be left blank in case the user has no email...I see in docs there is a way to make a rule for unique and an exception for an id...but I'm not sure how to make this allow null or blank but unique if it is not. Sorry seems like this is simple but I can't think of the answer.
public static $adminrules =
'email' => 'email|unique:users,email,null,id,email,NOT_EMPTY'
);
Edit It may be that using the rule without required is enough since a blank or null would pass validation in those cases. I might have a related bug that making it so I can't add more than 1 blank email, so I can't verify this.
public static $adminrules =
'email' => 'email|unique:users'
);
I tried this. Adding 'nullable' before 'sometimes'.
$validator = Validator::make($request->all(), [
'email' => 'nullable|sometimes|unique:users',
]);
You should try this:
$v->sometimes('email', 'email|unique:users,email', function($input)
{
return !empty($input->email);
});
$v is your validator object and you basically say that in case the email field is not empty it should also be unique (there shouldn't be a users table record with this value in email column).
In your Requests/UserRequest you'd have something like
public function rules()
{
return [
'email' => [
'nullable',Rule::unique((new User)->getTable())->ignore($this->route()->user->id ?? null)
]
];
}
The usage of nullable is what allows the field to be nullable. The other part is to check if the email is unique in the User model table.
If you wish to validate if the field is unique
between two fields please refer to this answer.
in another table, then add the following to your rules
'exists:'.(new ModelName)->getTable().',id'
You should try to change your structure of database to make the field email is nullable. And in the rules try this :
$this->validate($request,
[
'email' => 'email',
]
);
if(isset($request->address))
{
$this->validate($request,
[
'email' => 'email|unique:users'
]
);
}

Categories