Option 1: place it in your controller and call it like you would any class.
// $attribute = studentId
// $value = idOfStudent (just so you understand the difference)
// parameters - no in your case
// I'm assuming your model is Student and you've have imported it
public function doLogin()
{
Validator::extend('isStudent', function($attribute, $value, $parameters)
{
return Student::find(idOfStudent);
});
// rest of your code
// $results = Validator::make(Input::all(), $rules, $messsages);
}
Option 2 , which is the right way would be to create a StudentValidationClass and ServiceProvider
1. Note this requires more effort to setup, but cleaner and more extensible
2. Note - I have not tested or run any of this code.
3. Create directory App/Validators/
4. Create a class StudentValidationClass (or whatever you want to call it)
5. Create a method for it, example, hasStudent()
<?php namespace App\Validators;
class StudentValidator extends \Illuminate\Validation\Validator {
// 1. you must extend the class Validator class
// 2. the advantage of this is you can also create methods for your other student validation values as well as other student validation attributes, like isPaid
public function hasStudent($attribute, $value, $parameters)
{
// in this case value is idOfStudent
return Student::find($value);
}
// you can make this more sophisticated than just returning an array, but for this example
public function getStudentRules()
{
return [
'studentid' => 'required|idOfStudent',
'password' => 'required|alphaNum|min:2'
];
}
public function getStudentMessages()
{
return [
'studentid.required' => 'Please submit a student id.',
'istudentid.idOfStudent' => 'No such student exists.'
];
}
}
Now you create a ServiceProvider to hook it up.
<?php namespace App\Validators;
use Illuminate\Support\ServiceProvider;
class StudentServiceProvider extends ServiceProvider {
public function register(){}
public function boot()
{
$this->app->validator->resolver(function( $translator, $data, $rules, $messages )
{
return new StudentValidator($translator, $data, $rules, $messages );
});
}
}
Now we just need to tell Laravel to load this Service Provider and we would be all set.
Open up your app/config/app.php and in the providers array add the following at the end:
'App\Validators\StudentServiceProvider',
run composer sump-autoload