Laravel 4:将从存储库获取的验证消息传递给控制器

时间:2013-09-29 01:24:10

标签: php validation laravel inversion-of-control laravel-4

了解Ioc和Repositories并坚持到最后一步!

假设我正在验证输入,如何将存储库中Validator的消息传回控制器?

UserRepository

interface UserRepository {
    public function all();
    public function create($input);
    public function findById($id);
}

Sentry2UserRepository

class Sentry2UserRepository implements UserRepository {
...
public function create($input) {
        $validation = Validator::make($input, User::$rules);
        if ($validation->passes()) {
    Sentry::createUser( array_except( $input, ['password_confirmation']));

            // Put something here to tell controller that user has been successfully been created
            return true;
        }
        else {
            // pass back to controller that validation has failed
            // with messages
            return $validation->messages(); ?????     
        }       
...

我的UserController

UserController extends BaseController {
    ...
    public function postRegister() {
    $input['first_name'] = Input::get('first_name');
    $input['last_name'] = Input::get('last_name');
    $input['email'] = Input::get('email');
    $input['password'] = Input::get('password');
    $input['password_confirmation'] = Input::get('password_confirmation');


        // Something like
        if ($this->user->create($input)) {
            Session::flash('success', 'Successfully registered');
            return Redirect::to('/');
        }
        else {
            Session::flash('error', 'There were errors in your submission');
            return Redirect::to('user/login')->withErrors()->withInput();
        }
    }
    ...
}

进入Laravel只需1.5周,所以请放轻松。

1 个答案:

答案 0 :(得分:0)

假设您的存储库已经正常工作:

class Sentry2UserRepository implements UserRepository {
    public $validation;

    public function create($input) {
            $this->validation = Validator::make($input, User::$rules);
            if ($this->validation->passes()) {
                Sentry::createUser( array_except( $input, ['password_confirmation']));

                // Put something here to tell controller that user has been successfully been created
                return true;
            }
            else {
                // pass back to controller that validation has failed
                // with messages
                return false;     
            }
    }     

}

然后你只需要使用

在你的控制器中访问它
$this->user->validation->messages()