简体   繁体   中英

Laravel 4: Pass validation messages obtained from repository to controller

Learning about Ioc and Repositories and stuck at last hurdle!

Assuming I am validating input, how do I pass back messages from the Validator within the repository to the controller?

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(); ?????     
        }       
...

My 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();
        }
    }
    ...
}

Only 1.5 weeks into Laravel so please go easy on me.

Assuming your repository is working fine for you already:

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;     
            }
    }     

}

Then you just have to access it within your controller using

$this->user->validation->messages()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM