Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

php - Displaying the Error Messages in Laravel after being Redirected from controller

How can I display the validation message in the view that is being redirected in Laravel ?

Here is my function in a Controller

public function registeruser()
{
    $firstname = Input::get('firstname');
    $lastname = Input::get('lastname');
    $data  =  Input::except(array('_token')) ;
    $rule  =  array(
                'firstname'       => 'required',
                'lastname'         => 'required',
                   ) ;
    $validator = Validator::make($data,$rule);
    if ($validator->fails())
    {
    $messages = $validator->messages();
    return Redirect::to('/')->with('message', 'Register Failed');
    }
    else
    {
    DB::insert('insert into user (firstname, lastname) values (?, ?)',
                                array($firstname, $lastname));
    return Redirect::to('/')->with('message', 'Register Success');
    }
    }

I know the below given code is a bad try, But how can I fix it and what am I missing

@if($errors->has())
    @foreach ($errors->all() as $error)
        <div>{{ $error }}</div>
    @endforeach
@endif

Update : And how do I display the error messages near to the particular fields

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Laravel 4

When the validation fails return back with the validation errors.

if($validator->fails()) {
    return Redirect::back()->withErrors($validator);
}

You can catch the error on your view using

@if($errors->any())
    {{ implode('', $errors->all('<div>:message</div>')) }}
@endif

UPDATE

To display error under each field you can do like this.

<input type="text" name="firstname">
@if($errors->has('firstname'))
    <div class="error">{{ $errors->first('firstname') }}</div>
@endif

For better display style with css.

You can refer to the docs here.

UPDATE 2

To display all errors at once

@if($errors->any())
    {!! implode('', $errors->all('<div>:message</div>')) !!}
@endif

To display error under each field.

@error('firstname')
    <div class="error">{{ $message }}</div>
@enderror

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...