简体   繁体   中英

Validation using Sentry2 in Laravel 4

I want to use Sentry2 in my Laravel 4 application but I'm not sure how to use it to validate user submitted data before I interact with it. In my own models, I would write a $rules array to contain the validation rules and write a static validates() method that I could call in the controller.

But with Sentry2, how do I do this? Do I have to extend the User model that Sentry2 provides and use that instead? Or is there a way that Sentry allows me to add validation rules with extending it?

If I do extend the Sentry2 User model, do I extend it like so:

/app/models/User.php

class User extends \Cartalyst\Sentry\Users\Eloquent\User {

    private static $rules = array(...);

    public static validates($input, static::$rules) {...};
}

I then need to create my own config file instead of using the one that Sentry provides. I do the following in artisan:

php artisan config:publish cartalyst\sentry

and update the config file like so:

/app/config/packages/cartalyst/sentry/config.php

'users' => array()
    'model' => 'User',
;

Is this correct? If so, do I just call the model to validate user submitted data like I normally would? So, for example, in the UsersController I would check input by doing:

$validator = User::validate(Input::all());

I believe you are on the right way. Sentry doesn't really do any validation when you're saving data (except for checking for a password and a login field), and if you want to use validation from directly within the Eloquent model, you can extend the current Cartalyst user model, exactly as you have done in your code.

In the config file, you may have to take your namespaces in account. To check that Sentry really is using your model, try getting the currently logged in user (Sentry::getUser()) and var_dump it (dd(Sentry::getUser()) to see that Sentry is really using your class).

After you've got that setup, you can use your Eloquent model and validation as you normally would, with the addition of having all Sentry methods and properties.

If you want to keep the validation logic separate from you model, you can have a look at using validation as a service: http://culttt.com/2013/07/29/creating-laravel-4-validation-services/

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