2

How can I forward the custom value to error variable if a condition is met? I am doing a validation on user creation, and everything works except when I use the existing e-mail (which is unique in DB), which then crashes the app.

It would be great if that could be done in CreateUserRequest but I found no such thing, so I am filtering it out in controller.

Returning JSON worked like so:

public function store(CreateUserRequest $request)
{
    if (User::whereEmail($request['email'])->first()) {
       return Response::json([
                'error' => 'User with given e-mail already exists',
            ], 409);
    else {
        $user = User::create($request->all());
        return redirect('user');
        }
}

But in my view I have:

@if ($errors->has('email'))
<span class="help-block" style="color: red">
    <strong>
    {{ $errors->first('email') }}
    </strong>
</span>
@endif

So I was wondering if there is a way to forward a message from my controller to global $error variable?

1
  • 1
    You can add in rules method in CreateUserRequest, 'email' => 'required|unique'. It will not post the request to controller until this rule is validated Commented Apr 21, 2016 at 7:59

2 Answers 2

3

use

return Redirect::back()->withErrors(['email', 'The Message']);

but better approch would be to check this in CreateUserRequest validation.

// rules
'email' => 'required|unique:users',
Sign up to request clarification or add additional context in comments.

Comments

3

You can do it like that:

public function store(CreateUserRequest $request){

    if (User::whereEmail($request->email)->exists()) 
       return redirect()->back()->withErrors(['email' => 'User with given e-mail already exists']);

    $user = User::create($request->all());
    return redirect('user');

}

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.