Reputation: 49
This is my insert function in controller. How can I validate $establishment_code as unique with validatedData? Now I am using $check to validate that. But I want to validate it with validatedData.
public function establishment_insert(Request $request){
$validatedData = $request->validate([
'name' => 'required|max:190',
'code' => 'required|max:2',
'district-id' => 'required|max:20',
]);
$establishment_code = 'AS'.strtoupper(request('code'));
$check = Establishment::where('code', '=', $establishment_code)->first();
if($check){
return redirect('establishments/'.$establishment->district_id)->with('failed', 'Establishment code already exists!');
} else{
// Insert to db.
}
}
Upvotes: 0
Views: 8988
Reputation: 5662
Laravel has inbuilt validation rule named unique
. You can use unique
for the same
'code' => 'required|max:2|unique:establishments,code',
Laravel -> Validation -> Rule Unique
Upvotes: 0
Reputation: 5731
Change your validate as below :
$validatedData = $request->validate([
'name' => 'required|max:190',
'code' => 'required|max:2',
'district-id' => 'required|max:20',
'code' => [function ($attribute, $value, $fail) {
$establishment_code = 'AS'.strtoupper($value);
$check = Establishment::where('code', '=', $establishment_code)->first();
if (!$check) {
$fail(':attribute not found'); // error massage
}
}]
]);
Refer : https://laravel-news.com/custom-validation-rule-objects
Upvotes: 0
Reputation: 103
modify the request data
$request->merge([
'code' => 'AS'.strtoupper(request('code')),
]);
$validatedData = $request->validate([
'name' => 'required|max:190',
'code' => 'required|max:2|unique:establishments,code',
'district-id' => 'required|max:20',
]);
Upvotes: 0
Reputation: 4826
You try with Validator
use Illuminate\Support\Facades\Validator;
public function store(Request $request)
{
$data = $request->all();
$data['code'] = 'AS'.strtoupper(request('code'));
$validator = Validator::make($data, [
'name' => 'required|max:190',
'code' => 'required|max:2|unique:establishments',
'district-id' => 'required|max:20',
]);
if ($validator->fails()) {
return redirect('your route')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
Upvotes: 2