Laravel : Unique validation with different fields - laravel

I have a table states and fields are id,country_id,state_code,state_name.Now I want to validate that same country doesn't have a same state_code and same state_name in a table.
I tried but it's not working.
In my Controller :
$validator = State::validator($request->all(), $id);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator->getMessageBag())
->withInput($request->all());
}
Here is my validation function in model :
protected function validator(array $data, $id)
{
return Validator::make($data, [
'country_id' => 'required',
'state_code' => 'required',
'state_name' => 'required',
]);
}
How can I solved this without custom validation ?

First of all, your validation rules are only checking if these fields are present in the request. There is no validation happening for a value exists in database. First of all, you might wanna go through the documentation for the rule_exists. Secondly, you may have to update the query for this rule as per the documentation
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::exists('staff')->where(function ($query) {
$query->where('account_id', 1);
}),
],
]);
Here you can pass additional query parameters.

You do not need a custom validation for that one, laravel has a unique column validation
$this->validate($request, [
'country_id' => 'required',
'state_code' => 'required|unique:states,state_name',
'state_name' => 'required|unique:states,state_code',
]);
This way you know for sure that column values in state_code will be unique compare to state_name for more check the docs

Related

I have a problem with laravel validation logic when im trying to update my data

Hello guys im beginner in laravel and i need some help.I have a problem with my validation.When i store data in my bootstrap modal everyting is fine but when i press edit button and want to update, the same validation logic applies like when i create.When I want to update, if i don't change the name it won't update because it must be unique.
This is my Department Controller
public function store(Request $request)
{
$this->validate($request,[
'name'=>"required|unique:departments|max:255"
]);
$departmentId = $request->department_id;
Department::updateOrCreate(
['id' => $departmentId],
['name' => $request->name, 'description' => $request->description]
);
return response()->json(['success'=>'Department saved successfully.']);
}
As previously mentioned it would be ideal to have this be 2 different methods, but if you want this in one method you can achieve that. You will need to check if that department id is being passed or not to see if this is an update or create, then adjust the rule based on this. You can try something like this:
public function store(Request $request)
{
$unique = \Illuminate\Validation\Rule::unique('deparments');
if ($request->has('deparment_id')) {
$unique->ignore($request->department_id);
}
$this->validate($request, [
'name' => [
'required', $unique, 'max:255',
],
]);
$departmentId = $request->department_id;
Department::updateOrCreate(
['id' => $departmentId],
['name' => $request->name, 'description' => $request->description]
);
return response()->json(['success'=>'Department saved successfully.']);
}
This assumes the deparment_id is only passed for updates.
you can do this :-
$this->validate($request,[
'name' => 'required|unique:departments|max:255,'. $request->department_id,
]);

Laravel Unique Depends on Other Column

I have a table school_name and in form i want to apply 2 conditions if school name exist than branch must be unique
I tried below validation but its not working
'name' => 'required',
'branch' => 'required:unique:school_name,name',
You can use Rule::unique to achieve your validation rule
use Illuminate\Validation\Rule;
$schoolname = "abc";
$branch = "new";
Validator::make($data, [
'branch' => [
'required',
Rule::unique('tablename')->where(function ($query) use($schoolname ,$branch) {
return $query->where('school_name', $schoolname)->where('branch', $branch);
});
],
]);

how to make validation for two columns

I need a clean solution that's why I'm posting this.
So I have a formrequest validation which is the following:
public function rules()
{
return [
'restaurant_id' => 'required',
'rating' => 'required',
'comment' => 'required',
'visited_at' => 'required|date'
];
}
in controller, I also have user_id but request doesn't contain it. Now, I want to change the above rules so that user_id and restaurant_id both together will only be created only once. So for example . User_id 1 and restaurant_id 2 got saved as a row. If the same values come for these two columns, it should throw an error.
What would be the best and clean way?
You can expand the exists rule like this:
public function rules()
{
$user = $this->user();
return [
'restaurant_id' => [
'required',
Rule::exists('YOUR_TABLE_NAME')->where(function ($query) use ($user) {
$query->where('restaurant_id', request('restaurant_id'))
->where('user_id', $user->id);
})
],
'rating' => 'required',
'comment' => 'required',
'visited_at' => 'required|date'
];
}

i want each email to be unique for a certain field's id . how is it possible for validation in laravel 5

laravel 5
In laravel 5 form validation I need email to be only unique for a certain field's id in the db table.
$this->validate($request,[
'name'=>'required',
'email' => 'unique:users,email,',
'password'=>'required',
]);
You can try this way:
$companyId = $request->get('company_id'); // selected company
$this->validate($request,[
'name' => 'required',
'email' => [
'required',
"unique:users,email,NULL,id,company_id,$companyId"
],
'password'=>'required',
]);
If you want to ignore a specific id in the database, you can use ignore. For example, when a user is updating his profile, we want to allow him to send his email address, it should not be considered a not unique.
Here is the docs details. And here is your code updated to match that:
$this->validate($request,[
'name'=>'required',
'email' => [
\Illuminate\Validation\Rule::unique('users', 'email')->ignore($user->id),
],
'password'=>'required',
]);
However, if want to ignore more than one id or want to customize the query, you need to add a where clause:
$this->validate($request,[
'name' => 'required',
'email' => [
'required',
\Illuminate\Validation\Rule::unique('users')->where(function ($query) {
// Add any constraints you want for the query here.
return $query->whereNotIn('id', [1, 2, 3, 4]);
}),
],
'password'=>'required',
]);
Use Third and Fourth param to ignore for company_id
$company_id = 1;// Company will be here
And in validation
'email' => 'unique:users,email,'.$company_id.',company_id',

Custom Validation Laravel multiple attributes 5.5

In my form I have 2 attributes that need to be unique, I am trying to use Laravels Validator to do this but am very stuck..
Even if i add a return false/true to the function, there are no errors generated and the controller continues on. Am I missing something (not according to their docs :| )
$validator = Validator::make($request->all(), [
'organisationid' => 'required',
'membershipcode' => 'required'
]);
$validator->sometimes('membershipcode', 'required', function($input) {
return false;
});
In the store method in your controller, you can add validation like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique',
'description' => 'required',
]);
$movie = Model::create($request->all());
return redirect('view')->with('message', 'Added successfully');
}
The available validation rules are here: https://laravel.com/docs/5.5/validation#available-validation-rules

Resources