Laravel append rules on custom validation rule - php

In request I got attribute that defines validation rules and flow. Let's say it is account_type: business, personal.
Each value changes validation flow and requires different attributes to be present ir request.
Let's say I have following custom rules methods:
public function validateAccountTypeBusiness($attribute, $value, $parameters, Validator $validator)
{
// check is present:
// Company address
// VAT number
}
public function validateAccountTypePersonal($attribute, $value, $parameters, Validator $validator)
{
// check is present:
// User mobile phone
}
Since each rule requires more than single attribute to be presented in this request depending on account type ( vat number, company name, etc ) returning false would be not informative to user because generated response notices that account type is invalid without any details which actual attributes is missing.
The question is: how I can append more rules to be validated in this validation custom rule?
Following not working:
public function validateAccountTypeBusiness($attribute, $value, $parameters, Validator $validator)
{
$validator->addRules([
'company_address' => 'required|string',
'vat_number' => 'required',
]);
}

If you follow Complex Conditional Validation, you can validate using the following way
Step 1: Create Validator instance with static rules which would be same in both the cases(business or personal account) like name,check,phone,email,etc.
$v = Validator::make($data, [
'email' => 'required|email',
'name' => 'required|alpha',
'phone' => 'required|numeric',
'check' => 'required' //common in both account type
//add more rules as required
]);
Step 2: Add specific rules with condition
$v->sometimes('VAT', 'required|max:50', function ($input) {
return $input->account_type == 'business';
});
$v->sometimes('Company_address', 'required|max:500|alpha', function ($input) {
return $input->account_type == 'business';
});
$v->sometimes('user_mobile', 'required|numeric', function ($input) {
return $input->account_type == 'personal';
});
Parameters for sometimes() method :
The first argument passed to the sometimes method is the name of the
field we are conditionally validating. The second argument is the
rules we want to add. If the Closure passed as the third argument
returns true, the rules will be added.

As per my understanding, Custom validation rule can be used for only one parameter & you're trying to club them together.
This is one of many ways to approach your problem. Hope it helps.
<?php
namespace App\Http\Controllers;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AccountController extends Controller
{
/**
* Store a new user account.
*
* #param Request $request
* #return Response
*/
public function store(Request $request)
{
if($request->input('account_type' == 'business') {
// Validation for business account
$validator = Validator::make($request->all(), [
'company_address' => 'required|string',
'vat_number' => 'required',
]);
}
else {
// Validation for personal account
$validator = Validator::make($request->all(), [
'contact_number' => 'required',
]);
}
if ($validator->fails()) {
return redirect('account/create')
->withErrors($validator)
->withInput();
}
// Store the user account...
}
}
Reference -
Manually creating validators -
https://laravel.com/docs/5.4/validation#manually-creating-validators

Related

Can i ignore unique value when update record laravel 5.8? [duplicate]

I have a Laravel User model which has a unique validation rule on username and email. In my Repository, when I update the model, I revalidate the fields, so as to not have a problem with required rule validation:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray());
$user->save();
return $user;
}
This fails in testing with:
ValidationException: {"username":["The username has already been
taken."],"email":["The email has already been taken."]}
Is there a way of fixing this elegantly?
Append the id of the instance currently being updated to the validator.
Pass the id of your instance to ignore the unique validator.
In the validator, use a parameter to detect if you are updating or creating the resource.
If updating, force the unique rule to ignore a given id:
//rules
'email' => 'unique:users,email_address,' . $userId,
If creating, proceed as usual:
//rules
'email' => 'unique:users,email_address',
Another elegant way...
In your model, create a static function:
public static function rules ($id=0, $merge=[]) {
return array_merge(
[
'username' => 'required|min:3|max:12|unique:users,username' . ($id ? ",$id" : ''),
'email' => 'required|email|unique:member'. ($id ? ",id,$id" : ''),
'firstname' => 'required|min:2',
'lastname' => 'required|min:2',
...
],
$merge);
}
Validation on create:
$validator = Validator::make($input, User::rules());
Validation on update:
$validator = Validator::make($input, User::rules($id));
Validation on update, with some additional rules:
$extend_rules = [
'password' => 'required|min:6|same:password_again',
'password_again' => 'required'
];
$validator = Validator::make($input, User::rules($id, $extend_rules));
Nice.
Working within my question:
public function update($id, $data) {
$user = $this->findById($id);
$user->fill($data);
$this->validate($user->toArray(), $id);
$user->save();
return $user;
}
public function validate($data, $id=null) {
$rules = User::$rules;
if ($id !== null) {
$rules['username'] .= ",$id";
$rules['email'] .= ",$id";
}
$validation = Validator::make($data, $rules);
if ($validation->fails()) {
throw new ValidationException($validation);
}
return true;
}
is what I did, based on the accepted answer above.
EDIT: With Form Requests, everything is made simpler:
<?php namespace App\Http\Requests;
class UpdateUserRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'name' => 'required|unique:users,username,'.$this->id,
'email' => 'required|unique:users,email,'.$this->id,
];
}
}
You just need to pass the UpdateUserRequest to your update method, and be sure to POST the model id.
Unique Validation With Different Column ID In Laravel
'UserEmail'=>"required|email|unique:users,UserEmail,$userID,UserID"
or what you could do in your Form Request is (for Laravel 5.3+)
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'. $this->user
//here user is users/{user} from resource's route url
];
}
i've done it in Laravel 5.6 and it worked.
'email' => [
'required',
Rule::exists('staff')->where(function ($query) {
$query->where('account_id', 1);
}),
],
'email' => [
'required',
Rule::unique('users')->ignore($user->id)->where(function ($query) {
$query->where('account_id', 1);
})
],
Laravel 5 compatible and generic way:
I just had the same problem and solved it in a generic way. If you create an item it uses the default rules, if you update an item it will check your rules for :unique and insert an exclude automatically (if needed).
Create a BaseModel class and let all your models inherit from it:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model {
/**
* The validation rules for this model
*
* #var array
*/
protected static $rules = [];
/**
* Return model validation rules
*
* #return array
*/
public static function getRules() {
return static::$rules;
}
/**
* Return model validation rules for an update
* Add exception to :unique validations where necessary
* That means: enforce unique if a unique field changed.
* But relax unique if a unique field did not change
*
* #return array;
*/
public function getUpdateRules() {
$updateRules = [];
foreach(self::getRules() as $field => $rule) {
$newRule = [];
// Split rule up into parts
$ruleParts = explode('|',$rule);
// Check each part for unique
foreach($ruleParts as $part) {
if(strpos($part,'unique:') === 0) {
// Check if field was unchanged
if ( ! $this->isDirty($field)) {
// Field did not change, make exception for this model
$part = $part . ',' . $field . ',' . $this->getAttribute($field) . ',' . $field;
}
}
// All other go directly back to the newRule Array
$newRule[] = $part;
}
// Add newRule to updateRules
$updateRules[$field] = join('|', $newRule);
}
return $updateRules;
}
}
You now define your rules in your model like you are used to:
protected static $rules = [
'name' => 'required|alpha|unique:roles',
'displayName' => 'required|alpha_dash',
'permissions' => 'array',
];
And validate them in your Controller. If the model does not validate, it will automatically redirect back to the form with the corresponding validation errors. If no validation errors occurred it will continue to execute the code after it.
public function postCreate(Request $request)
{
// Validate
$this->validate($request, Role::getRules());
// Validation successful -> create role
Role::create($request->all());
return redirect()->route('admin.role.index');
}
public function postEdit(Request $request, Role $role)
{
// Validate
$this->validate($request, $role->getUpdateRules());
// Validation successful -> update role
$role->update($request->input());
return redirect()->route('admin.role.index');
}
That's it! :) Note that on creation we call Role::getRules() and on edit we call $role->getUpdateRules().
I have BaseModel class, so I needed something more generic.
//app/BaseModel.php
public function rules()
{
return $rules = [];
}
public function isValid($id = '')
{
$validation = Validator::make($this->attributes, $this->rules($id));
if($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
In user class let's suppose I need only email and name to be validated:
//app/User.php
//User extends BaseModel
public function rules($id = '')
{
$rules = [
'name' => 'required|min:3',
'email' => 'required|email|unique:users,email',
'password' => 'required|alpha_num|between:6,12',
'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
];
if(!empty($id))
{
$rules['email'].= ",$id";
unset($rules['password']);
unset($rules['password_confirmation']);
}
return $rules;
}
I tested this with phpunit and works fine.
//tests/models/UserTest.php
public function testUpdateExistingUser()
{
$user = User::find(1);
$result = $user->id;
$this->assertEquals(true, $result);
$user->name = 'test update';
$user->email = 'ddd#test.si';
$user->save();
$this->assertTrue($user->isValid($user->id), 'Expected to pass');
}
I hope will help someone, even if for getting a better idea. Thanks for sharing yours as well.
(tested on Laravel 5.0)
A simple example for roles update
// model/User.php
class User extends Eloquent
{
public static function rolesUpdate($id)
{
return array(
'username' => 'required|alpha_dash|unique:users,username,' . $id,
'email' => 'required|email|unique:users,email,'. $id,
'password' => 'between:4,11',
);
}
}
.
// controllers/UsersControllers.php
class UsersController extends Controller
{
public function update($id)
{
$user = User::find($id);
$validation = Validator::make($input, User::rolesUpdate($user->id));
if ($validation->passes())
{
$user->update($input);
return Redirect::route('admin.user.show', $id);
}
return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);
}
}
If you have another column which is being used as foreign key or index then you have to specify that as well in the rule like this.
'phone' => [
"required",
"phone",
Rule::unique('shops')->ignore($shopId, 'id')->where(function ($query) {
$query->where('user_id', Auth::id());
}),
],
I am calling different validation classes for Store and Update. In my case I don't want to update every fields, so I have baseRules for common fields for Create and Edit. Add extra validation classes for each. I hope my example is helpful. I am using Laravel 4.
Model:
public static $baseRules = array(
'first_name' => 'required',
'last_name' => 'required',
'description' => 'required',
'description2' => 'required',
'phone' => 'required | numeric',
'video_link' => 'required | url',
'video_title' => 'required | max:87',
'video_description' => 'required',
'sex' => 'in:M,F,B',
'title' => 'required'
);
public static function validate($data)
{
$createRule = static::$baseRules;
$createRule['email'] = 'required | email | unique:musicians';
$createRule['band'] = 'required | unique:musicians';
$createRule['style'] = 'required';
$createRule['instrument'] = 'required';
$createRule['myFile'] = 'required | image';
return Validator::make($data, $createRule);
}
public static function validateUpdate($data, $id)
{
$updateRule = static::$baseRules;
$updateRule['email'] = 'required | email | unique:musicians,email,' . $id;
$updateRule['band'] = 'required | unique:musicians,band,' . $id;
return Validator::make($data, $updateRule);
}
Controller:
Store method:
public function store()
{
$myInput = Input::all();
$validation = Musician::validate($myInput);
if($validation->fails())
{
$key = "errorMusician";
return Redirect::to('musician/create')
->withErrors($validation, 'musicain')
->withInput();
}
}
Update method:
public function update($id)
{
$myInput = Input::all();
$validation = Musician::validateUpdate($myInput, $id);
if($validation->fails())
{
$key = "error";
$message = $validation->messages();
return Redirect::to('musician/' . $id)
->withErrors($validation, 'musicain')
->withInput();
}
}
public static function custom_validation()
{
$rules = array('title' => 'required ','description' => 'required','status' => 'required',);
$messages = array('title.required' => 'The Title must be required','status.required' => 'The Status must be required','description.required' => 'The Description must be required',);
$validation = Validator::make(Input::all(), $rules, $messages);
return $validation;
}
I had the same problem.
What I've done: add in my view hidden field with id of a model and in validator check the unique, only if I've get some id from view.
$this->validate(
$request,
[
'index' => implode('|', ['required', $request->input('id') ? '' : 'unique:members']),
'name' => 'required',
'surname' => 'required',
]
);
You can trying code bellow
return [
'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
'password' => 'required|min:6',
'confirm-password' => 'required|same:password',
];
Laravel 5.8 simple and easy
you can do this all in a form request with quite nicely. . .
first make a field by which you can pass the id (invisible) in the normal edit form. i.e.,
<div class="form-group d-none">
<input class="form-control" name="id" type="text" value="{{ $example->id }}" >
</div>
...
Then be sure to add the Rule class to your form request like so:
use Illuminate\Validation\Rule;
... Add the Unique rule ignoring the current id like so:
public function rules()
{
return [
'example_field_1' => ['required', Rule::unique('example_table')->ignore($this->id)],
'example_field_2' => 'required',
];
... Finally type hint the form request in the update method the same as you would the store method, like so:
public function update(ExampleValidation $request, Examle $example)
{
$example->example_field_1 = $request->example_field_1;
...
$example->save();
$message = "The aircraft was successully updated";
return back()->with('status', $message);
}
This way you won't repeat code unnecessarily :-)
public function rules()
{
if ($this->method() == 'PUT') {
$post_id = $this->segment(3);
$rules = [
'post_title' => 'required|unique:posts,post_title,' . $post_id
];
} else {
$rules = [
'post_title' => 'required|unique:posts,post_title'
];
}
return $rules;
}
For a custom FormRequest and Laravel 5.7+ you can get the id of your updated model like this:
public function rules()
{
return [
'name' => 'required|min:5|max:255|unique:schools,name,'.\Request::instance()->id
];
}
For anyone using a Form request
In my case i tried all of the following none of them worked:
$this->id, $this->user->id, $this->user.
It was because i could not access the model $id nor the $id directly.
So i got the $id from a query using the same unique field i am trying to validate:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
$id = YourModel::where('unique_field',$this->request->get('unique_field'))->value('id');
return [
'unique_field' => ['rule1','rule2',Rule::unique('yourTable')->ignore($id)],
];
}
It will work 100%
I have both case implement like One case is same form field in database table products and other is products_name is form field and in table, it's name is name, how we can validate and ignore that id while updating. I have encrypted that so i'm decrypted id, if you are encrypt then you will decrypt otherwise pass it as it's coming from the form.
$request->validate([
'product_code' => 'required|unique:products,product_code,'.decrypt($request->hiddenProductId),
'products_name' => 'required|unique:products,name,'.decrypt($request->hiddenProductId),
]);
there is detailed and straightforward answer to this question, I was looking for too
https://laravel.com/docs/9.x/validation#rule-unique

How to use Laravel 5.4 validator at web service for mobile application

I have a problem with Laravel 5.4 validator which is I'm trying to validate data comes from a mobile application but when validator fails it redirect to the home page. I need to prevent this redirect and return a json response with validation errors messages
Here's my route.php code
Route::group(['middleware' => 'web'], function() {
Route::post('/userSignUp', [
'uses' => 'UserController#userSignUp',
'as' => 'userSingUp'
]);
});
And this is my controller code
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
class UserController extends Controller
{
public function userSignUp(Request $request){
$fullName = $request->input('fullName');
$email = $request->input('email');
$phone = $request->input('phone');
$password = $request->input('password');
$userType = $request->input('userType');
$profilePic = $request->input('profilePic');
$validator = $this->validate($request, [
'fullName' => 'required|max:255',
'email' => 'required|email',
'phone' => 'required'
]);
if ($validator->fails()) {
return response()->json($validator->messages(), 200);
}
}
}
So can anyone help me solving this issue I need to use a laravel 5.4 validator in a web service for a mobile application so I need to prevent the validator redirecting as it does in the above code it redirecting to home page when validation is failed
thanks in advance
if the validation fails when you call $this->validate($request,$rules) laravel will throw an exception and a failed validation response will be sent back by this method define in Illuminate\Foundation\Validation\ValidatesRequests :
/**
* Create the response for when a request fails validation.
*
* #param \Illuminate\Http\Request $request
* #param array $errors
* #return \Symfony\Component\HttpFoundation\Response
*/
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->expectsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}
So it seems that Laravel does handle that by checking $request->expectsJson() so you need to specify the Accept header in you request to JSON, then a JSON formatted response with code 422 will be returned.
return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->withCallback($request->input('callback'));
from the official doc https://laravel.com/docs/5.4/responses#json-responses
And maybe try to make your validation in your model directly
class User extends Eloquent
{
private $rules = array(
'fullName' => 'required|max:255',
'email' => 'required|email',
'phone' => 'required|numeric'
);
public function validate($data)
{
// make a new validator object
$v = Validator::make($data, $this->rules);
// return the result
return $v->passes();
}
}
and in your controller you can make
$new = Input::all();
$u = new User();
if ($b->validate($new))
{
}
else
{
}

Laravel request firing twice with custom validation class

I have a weird problem with my Laravel application, whereby this code gets called twice once the validation rules kick in. I have abstracted validation logic into a separate class, but no matter how I consume the API (tried using Postman, and with jQuery) it still appears to run twice with the output looking like this:
called{"email":["The email has already been taken."],"country":["The country must be a number."]}called{"email":["The email has already been taken."],"country":["The country must be a number."]}
I am only expecting one JSON response. I'm tearing my hair out, tried on two different connections and can't seem to work out why the custom request is called twice. This is a new Laravel app, so there isn't much code to conflict with it.
//Create User Request extends standard request. Handles Validation
public function __construct(CreateUserRequest $request){
$this->request = $request;
}
public function register()
{
try{
$array = DB::transaction(function(){
$email = $this->request->input('email');
$password = $this->request->input('password');
$companyName = $this->request->input('companyName');
$userName = $this->request->input('name');
$country = $this->request->input('country');
$company = Company::create([
'name' => $companyName,
'active'=>true,
'country_id'=>$country
]);
$user = User::create([
'company_id' => $company->id,
'name'=>'admin',
'email' => $email,
'password' => $password,
'active' =>true
]);
if( !$company || !$user )
{
throw new \Exception('User not created for account');
}
return compact('company', 'user');
});
$token = JWTAuth::fromUser($array['user']);
return Response::json(compact('token'));
}
catch( Exception $e )
{
return Response::json(['error' => $e->getMessage() ], HttpResponse::HTTP_CONFLICT );
}
}
Then the validation custom Request..
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Response;
class CreateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
public function response(array $errors)
{
// return Response::json(['errorg' => $errors ], 200 );
echo('called');
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => 'required|unique:users',
'password' => 'required',
'companyName' => 'required',
'name' => 'required',
'country' => 'required|numeric'
];
}
}
Interesting.
Try to remove CreateUserRequest $request parameter from __construct() and add it to your register() method like this: register(CreateUserRequest $request). And use your request by calling $request instead of $this->request.

Having common validation function across multiple controller in laravel

Trying my hand on learning laravel.
I have a user form which post to this route
Route::post('users/add','usersController#store')->middleware('admin');
The store function in the usersController calls another function called validateForm which basically validates the input from the form ,like so
class usersController extends Controller
{
/*
*Store a user in database
*/
function store(){
$input=Request::all();
// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'lastname' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the users table
'password' => 'required',
);
$validationResponse=$this->validateForm($input,$rules);
if($validationResponse=="passed"){
$user=new \App\User;
$user->name=$input['name'];
$user->email=$input['email'];
$user->lastname=$input['lastname'];
$user->password=\Hash::make($input['password']);
$user->userlevel=isset($input['isAdmin'])?1:0;
$user->save();
return redirect('users');
}
else{
return Redirect::to('users/create')
->withErrors($validationResponse)->withInput();
}
}
/*
*validate user form input
*/
function validateForm($input,$rules){
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make($input, $rules);
// check if the validator failed -----------------------
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
return $messages;
}
else{
return 'passed';
}
}
}
Now this is fine for accesing from the userController, but what if I have another controller say projectsController and I want to access the same funtion i.e. validateForm
Where I should put this common function and how can I access it from any controller?
Laravel built in answer to this is Form Request
Just create a form request using php artisan make:request UserCheck, and put in your validation rules in the method rules
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
return [
'name' => 'required', // just a normal required validation
'lastname' => 'required', // just a normal required validation
'email' => 'required|email|unique:users', // required and must be unique in the users table
'password' => 'required',
]; }
And call it
/*
* Store a user in database
*/
public function store(UserCheck $request)
{
// The incoming request is valid...
}

Laravel registration. Register only users that own an email from a specific domain

I have a laravel app and I want to limit the users registered only to a specific target group that owns an email from a company. I have tried something in my Registrar.php
public function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'lastname' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
public function create(array $data)
{
$result = null;
$confirmation_code = str_random(30);
$data = array_add($data, 'conf',$confirmation_code);
if(!$data['email'].ends_with(('email'), 'specificdomain.com')){
Flash::message('Welcome ' .$data["name"]. '. Thanks for registering. We have sent you a validation link in your e-mail address!');
Mail::send('emails.verify', $data, function($message) use ($data) {
$message->to($data['email'], $data['name'])
->subject('Verify your email address');
});
$result = User::create([
'name' => $data['name'],
'lastname' => $data['lastname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'confirmation_code' => $confirmation_code
]);
}else{
$result = Flash::warning('Hi ' .$data["name"]. '. We appreciate your interest on using our System. However at the moment we offer this service only to this company!');
//break;
}
return $result;
}
This throws the following exception
Argument 1 passed to Illuminate\Auth\Guard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, Laracasts/Flash/Flash given.
And i cannot break at the else statement because i get the following:
Cannot break/continue 1 level
Apparently I have to return Users::create([....]) but to do so I have to keep this block outside of the if statement. If I do that i cannot check if the email domain is the required one. So I am asking, how can I integrate this in the public function validator(array $data){.....} block?
All the help is appreciated.
You could expand the email validation in your validator rules like:
'email' => 'required|email|max:255|unique:users|regex:/(.*)your\.domain\.com$/i',
(or pass it as an array if you need to pipe in your regex)
You can then add an array of messages to your validator like:
$messages = array(
'email.regex' => 'We appreciate your interest on using our System. However at the moment we offer this service only to this company!',
);
Where you call the Validator add messages as 3rd argument:
// Where $rules is the array you pass on now
$validator = Validator::make($data, $rules, $messages);
In the laravel documentation you can ready everything about responses.
You can not return a Flash. You can use Flash to (in your case) put a message into the Session, that will be removed after the request. I'm not entirely sure how you call the create function and what the expected result that is returned should be, but I would be consistent with this. Since you can now solve it with a validation message, you should only have to Flash a success message or an error.
I recently faced this issue using Laravel v5.3 and solved it by extending the Validator facade. The rule consisted of:
'email' => 'required|email|allowed_domain|max:255|unique:users'
And the extension was put into the app/Providers/AuthServiceProvider.php boot method:
Validator::extend('allowed_domain', function($attribute, $value, $parameters, $validator) {
return in_array(explode('#', $value)[1], $this->allowedDomains);
}, 'Domain not valid for registration.');
$this->allowedDomains being an array of allowed domains.

Categories