Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set "custom" withErrors without Request->validation in Laravel

I want to display an error in a form, but it cannot be checked via validation.

Blade

    <form action="/githubuser" methode="GET">
        <div class="error">{{ $errors->first('CustomeError') }}</div>
        <input type="text" name="userName" placeholder="GitHub Username ..." value="John12341234">
        @if($errors->has('userName'))
            <div class="error">{{ $errors->first('userName') }}</div>
        @endif            
        <input type="submit" value="SUBMIT">
    </form>

The Problem is that I start an api call after validation. and if I don’t get "GitHubUser" as a response, I want to print an error message in the blade. GitHub user not found.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Controller

    public function show(Request $request)
    {
        $rules = ['userName' => 'required'];
        $validator = \Validator::make($request->input(), $rules);
        
        if ($validator->fails()) {
            return redirect('/')
                    ->withErrors($validator)
                    ->withInput();
        }
        
        $data = $this->gitHubUserService->getUserData($request->input('userName'));
        /* User on Github not Found **/
        if (! $data) {
            // >>> THE LINE BELOW IS MY PROBLEM! <<<
            return view('form')->withErrors($validator);
        }

        // ....
     }

At the end of the day I want the line <div class="error">{{ $errors->first('CustomeError') }}</div> to be displayed in the blade.

Is this possible? Thanks in advance!

>Solution :

The original validator is not getting any error, because there are none. So, just add a new error to the errors inside of your if body before returning form view:

if(! $data){
    $validator->errors()->add('customError', 'Github User not found!');
    return view('form')->withErrors($validator);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading