Thomas De Marez
Thomas De Marez

Reputation: 666

Add error to validation errors using formRequest

i'm trying to figure out how to add a error message to the default $error generated by the Illuminate\Support\MessageBag when using validation trough requests.

I've searched on google and the laravel docs and not really found information clarifying this for me.

AuthController

<?php
namespace App\Http\Controllers\Auth;

use Auth;
use App\User;
use App\Http\Requests\LoginFormRequest;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

/*
 * AuthController
 */
class AuthController extends Controller {
    /*
     * Create view
     *
     * @return View
     */
    public function getLogin() {
        return view('auth.login');
    }

    /*
     * Validate Login
     *
     * @return Redirect route
     */
    public function postLogin(LoginFormRequest $request) {
        if (Auth::attempt(array('email' => $request->email, 'password' => $request->password), $request->remember)) {
            return redirect()->intended('home')->with('success-message', 'Succesfully authenticated');
        } else {
            $validator->addMessage('Incorrect email and password combination');
            return redirect('account.login')->withErrors($validator)->withInput();
        }
    }
}

LoginFormRequest

<?php 

namespace App\Http\Requests;

use Response;
use Illuminate\Foundation\Http\FormRequest;

class LoginFormRequest extends FormRequest {

    public function rules() {
        return array(
            'email'    => 'required|email',
            'password' => 'required|between:8,20'
        );
    }

    public function authorize() {
        return true;
    }
}

Hopefully someone has encountered this problem before and can help me!

Upvotes: 4

Views: 2118

Answers (2)

cre8
cre8

Reputation: 13562

$validator->getMessageBag()->add("password", "Username and/or password don't match.");

Will add an error for this field.

Upvotes: 1

kielabokkie
kielabokkie

Reputation: 398

Just add the messsages() function to your LoginFormRequest class:

public function messages()
{
    return array(
        'email.required' => 'The email address is required.',
        'password.required' => 'The password is required.',
        'password.between' => 'The password should be between 8 and 20 characters.',
    );
}

Using the dot notation, you specify the field first and then the type of validator.

Upvotes: 3

Related Questions