Jason
Jason

Reputation: 4772

Add a message to the $error MessageBag

This is Laravel 4.2

Laravel will make the $error MessageBag available to views. This can be populated with flash messages in the previous page by redirecting ->withErrors(). That is fine if you are redirecting to a new page.

return Redirect::route('my_route')->withErrors($validator);

I am generating some errors in the controller, not validating a form, and want to put those messages into the $errors MessageBag that Laravel automatically passes into the views. But how? The MessageBag is somewhere, but how do I get to it, and how do I add some messages to it to display in the current page?

Upvotes: 6

Views: 35240

Answers (4)

Luís Cruz
Luís Cruz

Reputation: 14970

I have done that with some custom validations. What you need is something like this:

use Illuminate\Support\MessageBag;

class MyCustomValidator
{
    protected $errors = array();

    protected $messageBag;

    public function __construct(MessageBag $messageBag)
    {
        $this->messageBag = $messageBag;
    }

    public function setErrors($errors = array())
    {
        for($i = 0; $i < count($errors); $i++) {
            $this->messageBag->add($i, $errors[$i]);
        }

        $this->errors = $this->messageBag;
    }

    public function getErrors()
    {
        return $this->errors->all();
    }
}

In your controller you have to call something like

$validator = new MyCustomValidator();
$validator->getErrors();

You can access the full documentation for the MessageBag in the docs.

Upvotes: 6

Chintan7027
Chintan7027

Reputation: 7605

Be late but another solution to add custom message in error message bag is:

Controller

$rules = array(
        'email' => 'required|exists:users,email|email|max:32',
        'password' => 'required|max:20'
    );
    $validator = Validator::make($request->all(),$rules);


    $email = $request->email;
    $password = $request->password;

    $validateUser = new user();
    $users = $validateUser::where('email', $email)->get();
    if($users->isEmpty()){
        $validator->getMessageBag()->add('email', 'Invalid Email Address');    
        return redirect('home')->withErrors($validator);
    }
    foreach ($users as $user) {
        $data = $user->showAdminData();
        if($user->role_id!=1){
            $validator->getMessageBag()->add('email', 'Unauthorised access');
        }
        if(Crypt::decrypt($user->password)!==$password){
            $validator->getMessageBag()->add('password', 'Invalid Password');
        }
    }
    return redirect('home')->withErrors($validator);

View

<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
                        <label class="col-md-4 control-label">E-Mail Address</label>

                        <div class="col-md-6">
                            <input type="email" class="form-control" name="email" value="{{ old('email') }}">

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

                    <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
                        <label class="col-md-4 control-label">Password</label>

                        <div class="col-md-6">
                            <input type="password" class="form-control" name="password">

                            @if ($errors->has('password'))
                            <span class="help-block">
                                <strong>{{ $errors->first('password') }}</strong>
                            </span>
                            @endif
                        </div>
                    </div>

Upvotes: 1

Han Hermsen
Han Hermsen

Reputation: 31

Laravel 5

$validator = .......

$validator->after(function($validator) {
    .....               
    $validator->errors()->add('tagName', 'Error message');
    .....
});

Mind that the anonimous function is in the scope of the class, not in that of the function where you use it. If you need the value of some variable from the outside world it must be a class variable!

Upvotes: 3

Jason
Jason

Reputation: 4772

It looks like I can inject messages when the view is created.

My controller passes the required view, with the data it collects, to the content of the page template like this:

$this->layout->content = View::make('my.view', $view_data);

Errors can be passed in like this:

$this->layout->content = View::make('my.view', $view_data)->withErrors($my_errors);

where $my_errors can be null or array() (for "no additional errors"), an array of text messages, or a MessageBag.

My outer page template then just picks up the messages if they exist, and displays them at the top of the page:

@if ( $errors->count() > 0 )
    ...An error occured...
    @foreach( $errors->all() as $message )
        ...{{ $message }}...
    @endforeach
@endif

(with markup where appropriate)

Upvotes: 11

Related Questions