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

Posted

技术标签:

【中文标题】Laravel 4:将从存储库获得的验证消息传递给控制器【英文标题】:Laravel 4: Pass validation messages obtained from repository to controller 【发布时间】:2013-10-05 02:13:42 【问题描述】:

了解 Ioc 和存储库并卡在最后一个障碍!

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

用户存储库

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 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】:

假设您的存储库已经可以正常运行:

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()

【讨论】:

以上是关于Laravel 4:将从存储库获得的验证消息传递给控制器的主要内容,如果未能解决你的问题,请参考以下文章

在 auth 上将附加错误消息传递给验证错误包

jquery .ajax函数与Laravel-4无法正常工作

Laravel Spark 中的自定义验证消息

如何将从地理位置获得的城市与我的数据库中存储的城市进行比较,如果城市存在,则通过 ajax 请求传递 id?

将自定义验证规则作为字符串传递并获取所有验证消息

Laravel - 显示传递给视图的消息数据