Web Student
Web Student

Reputation: 735

laravel 4 returning validation message error

I am currently just testing laravel 4, but i have a problem, in the laravel docs returning error messages is described this way $messages->first('email');should return the message, but no matter what methog id try on the messages i get error

my cobtroller

public function postSignup()
    {
        $rules = array(
            'display_name'     => 'required|unique:users',
        );

        $messages = array(
            'display_name.required' => 'Felhasználónév kötelező',
            'display_name.unique'   => 'Ez a Felhasználónév foglalt',
        );

        $val = Validator::make(Input::all(), $rules, $messages);

        if ($val->passes()) 
        {
            $data = array('msg' => 'yay');
        }
        else
        {
            print_r($messages->first('display_name'));
        }

        return Response::json($data);
    } 

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Call to a member function first() on a non-object"

if i try with all just for a test print_r($messages->all()); im getting the following

{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"Call to a member function all() on a non-object"

could please someone point out what i am doing wrong?

Upvotes: 1

Views: 5380

Answers (3)

The Alpha
The Alpha

Reputation: 146269

You may try this

if ($val->passes()) 
{
    $data = array('msg' => 'yay');
}
else
{
    $messages = $validator->messages();
    $data = array('msg' => $messages->first('display_name'));
}
return Response::json($data);

print_r(...); in the controller will print the output outside of the template. On the client side you can check the msg something like this (using jQuery for example)

$.get('url', function(data){
    if(data.msg == 'yay')
    {
        // success
    }
    else
    {
        // failed, so data.msg contains the first error message
    }
});

Upvotes: 3

Blessing
Blessing

Reputation: 4888

You are accessing the messages array you passed into the validator, not the error messages the validator created. Change your code to this:

$val->messages()->first('email')

NOTE: The validator::make method accepts 3 arguments:

/**
 * Create a new Validator instance.
 *
 * @param  array  $data
 * @param  array  $rules
 * @param  array  $messages
 * @return \Illuminate\Validation\Validator
 */
public function make(array $data, array $rules, array $messages = array())

Upvotes: 0

Chris Breslaw
Chris Breslaw

Reputation: 169

Validator::make method only accepts two arguments.

Upvotes: 0

Related Questions