Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Jenny Swift
Jenny Swift
21,999 Points

Laravel 5 custom validation/how to control who can register

Hi, so first of all, my goal: I want to be able to control who can register for my web application. My app has a lot of work to do before it is ready for the public, but I want a few people I know to be able to use it. I assume I would do this with a custom validation? For example, I would have an array of email addresses and when a new user tries to register, check if their email address matches one in my array.

I have Googled around and a lot of the talk on Laravel custom validations is for Laravel 4. I have looked at the docs, and as I often find, the docs alone aren’t enough for me to grasp how to do something, in this case, a custom validation. But anyway...

So I suppose in app/Services/Registrar.php, within the validator function, I would do:

'email' => 'required|email|max:255|unique:users|MyCustomValidationRule'

and then somewhere (I don’t know where?), I would do:

Validator::extend(‘MyCustomValidationRule', function($attribute, $value, $parameters) {
     $accepted_emails = array(‘john@example.com’, ‘jane@example.com');
     //I don’t understand what to do from here-how I would use my array, and what the following line does (from the docs). 
     return $value == 'foo';
});

Can anyone help me with this please? Or is there an easier/better way to control who can register?

1 Answer

Jenny Swift
Jenny Swift
21,999 Points

This worked for me:

Validator::extend('accepted_email', function ($attribute, $value, $parameters) {
    $accepted_emails = [
        'email1@example.com',
        'email2@example.com'
    ];
    $is_accepted = in_array($value, $accepted_emails);
    return $is_accepted;
});

Then I added accepted_email to the email value in the validator function in Registrar.php.