0

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.
            }
        }

4 Answers 4

2

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...
    }
Sign up to request clarification or add additional context in comments.

Comments

0

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',
            ]);

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.