I'm using laravel breeze as auth scaffolding package I want to know How can I
create two diffirent registration form for two User Types here is a simple explanation of hwat I want to achieve:
resources/auth/developer :
developer-register.blade.php
resources/auth/designer :
designer-register.blade.php
if the Visitor choose to register as "developer" it will display a diffirent form. and same thing for if the Visitor choose to register as "designer" it will display a diffirent form with fields.
I wish you understand what I want to achieve with this easy explanation.
Ok, so i've not used laravel/breeze myself (yet) but it shouldn't be much different from doing it in standard Laravel!
Views
By default, it looks like the breeze scaffolding is going to hit a create() method on the RegisteredUserController which will return a single view like so:
RegisteredUserController.php
/**
* Display the registration view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.register');
}
You have a few options here:
Replace this view with another
Add some logic to change the view which is returned based on the request being made (you can inject a Request object into the route like any other)
public function create(Request $request)
{
if ($request->has('developer')) {
return view('auth.developer-register');
} else {
return view('auth.designer-register');
}
}
Keep the original auth.register view and handle the logic in the blade template.
Registration
The forms on each of your registration pages will have an action that points to a controller route. This will likely be the RegisteredUserController within which you will find a store() method that handles the creation of a User model.
RegisteredUserController.php
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|confirmed|min:8',
]);
Auth::login($user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]));
event(new Registered($user));
return redirect(RouteServiceProvider::HOME);
}
As you can see, this store() method is handling the creation of a User model and then authenticating it before redirecting the user to the home route.
What you could do, is check the request for the the requested user type and then use a switch statement to change the type of use being created.
switch ($request->get('user_type'))
case 'developer':
$user = Developer::create([ /* add details here */ ]);
break;
case 'designer':
$user = Designer::create([ /* add details here */ ]);
break;
Auth::login($user);
I hope this will at least inspire you with your own solution!
I start with Laravel, I write API. I have a method in TestController that checks if the student has correctly inserted data and has access to the exam solution. I do not think it's a good idea to have the whole method in the controller, but I have no idea how to separate it. I think about politics, but I have to have several models for one policy, maybe I can try to put part of the method on AuthorizeStudentRequest or try it in a different way? Of course, now I am returning 200 with the message, but I have to return 422 or another code with errors, but I have not done it because of my problem.
public function authorizeStudent(AuthorizeStudentRequest $request)
{
$hash = $request->input('hash');
$token = $request->input('token');
$exam = Exam::where([['hash', $hash], ['token', $token]])->first();
if($exam == null)
return ['message' => 'Exam does not exist.'];
$user = $exam->user_id;
$studentFirstname = $request->input('firstname');
$studentLastname = $request->input('lastname');
$student = Student::where([
['firstname', $studentFirstname],
['lastname', $studentLastname],
['user_id', $user]
])->first();
if($student == null)
return ['message' => 'Student does not exist.'];
$classroom = Classroom::where([
['name', $classroomName],
['user_id', $user]
])->first();
if($classroom == null)
return ['message' => 'Classroom does not exist.'];
if($student->classroom_id != $classroom->id)
return ['message' => 'Student is not in classroom.'];
if($exam->classrooms()->where(['classroom_id', $classroom->id], ['access', 1])->first() == null)
return ['message' => 'Class does not access to exam yet.'];
}
I would suggest you rather pass the primary keys of the selected $exam, $student and $classroom models to your controller from the form and validate whether they exist in the corresponding tables, rather than having to check their existence using a bunch of different columns.
If you pass the primary keys, you could use the 'exists' validation rule to check if they exist. For example, in your AuthorizeStudentRequest class you could have the following function:
public function rules()
{
return [
'exam_id' => 'required|exists:exams',
'student_id' => 'required|exists:students',
'classroom_id' => 'required|exists:classrooms',
];
}
Otherwise, if you really need to use the different columns to check the existence of the exam, student and classroom, you could create custom validation rules and use them in your AuthorizeStudentRequest class. For example, create a custom validation rule that checks whether the exam exists as follows:
$php artisan make:rule ExamExists
class ExamExists implements Rule
{
private $token;
private $hash;
public function __construct($token, $hash)
{
$this->token = $token;
$this->hash = $hash;
}
public function passes($attribute, $value)
{
return Exam::where([['hash', $hash], ['token', $token]])->count() > 0;
}
}
And then you can use the custom validation rule in your request as follows:
public function rules()
{
return [
'hash' => ['required', new ExamExists($this->hash, $this->token)],
... other validation rules ...
]
}
For checking whether a student has access to a classroom or a class has access to an exam, you could use policies.
API resources present a way to easily transform our models into JSON responses. It acts as a transformation layer that sits between our Eloquent models and the JSON responses that are actually returned by our API. API resources is made of two entities: a resource class and a resource collection. A resource class represents a single model that needs to be transformed into a JSON structure, while a resource collection is used for transforming collections of models into a JSON structure.
Both the resource class and the resource collection can be created using artisan commands:
// create a resource class
$ php artisan make:resource UserResource
// create a resource collection using either of the two commands
$ php artisan make:resource Users --collection
$ php artisan make:resource UserCollection
Before diving into all of the options available to you when writing resources, let's first take a high-level look at how resources are used within Laravel. A resource class represents a single model that needs to be transformed into a JSON structure. For example, here is a simple User resource class:
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
Every resource class defines a toArray method which returns the array of attributes that should be converted to JSON when sending the response. Notice that we can access model properties directly from the $this variable. More information here
https://laravel.com/docs/5.7/eloquent-resources
In order to reuse code, I created my own validator rule in a file named ValidatorServiceProvider :
class ValidatorServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('checkEmailPresenceAndValidity', function ($attribute, $value, $parameters, $validator) {
$user = User::where('email', $value)->first();
// Email has not been found
if (! $user) {
return false;
}
// Email has not been validated
if (! $user->valid_email) {
return false;
}
return true;
});
}
public function register()
{
//
}
}
And I use this rule like this :
public function rules()
{
return [
'email' => 'bail|required|checkEmailPresenceAndValidity'
];
}
But, I want to set different error messages for each case, something like this :
if (! $user) {
$WHATEVER_INST->error_message = 'email not found';
return false;
}
if (! $user->valid_email) {
$WHATEVER_INST->error_message = 'invalid email';
return false;
}
But I don't figure out how to achieve this without doing 2 different rules ...
Of course it could work with multiple rules but it will also perform multiple SQL queries, and I really want to avoid that.
Also, keep in mind that in real case I could have more than 2 validations like theses in a single rule.
Does anyone have an idea ?
=====
EDIT 1 :
Actually, I think that I want something that works in a similar way to the between or size rules.
They represent one single rule, but provide multiple error messages :
'size' => [
'numeric' => 'The :attribute must be :size.',
'file' => 'The :attribute must be :size kilobytes.',
'string' => 'The :attribute must be :size characters.',
'array' => 'The :attribute must contain :size items.',
],
Laravel checks if the value represents a numeric, a file, a string or an array ; and gets the right error message to use.
How do we achieve this kind of thing with custom rule ?
Unfortunately Laravel doesn't currently provide a concrete way to add and call your validation rule directly from your attribute params array. But that does not exclude a potential and friendly solution based on Trait and Request usage.
Please find below my solution for example.
First thing is to wait for the form to be processed to handle the form request ourselves with an abstract class. What you need to do is to get the current Validator instance and prevent it from doing further validations if there's any relevant error. Otherwise, you'll store the validator instance and call your custom user validation rule function that you'll create later :
<?php
namespace App\Custom\Validation;
use \Illuminate\Foundation\Http\FormRequest;
abstract class MyCustomFormRequest extends FormRequest
{
/** #var \Illuminate\Support\Facades\Validator */
protected $v = null;
protected function getValidatorInstance()
{
return parent::getValidatorInstance()->after(function ($validator) {
if ($validator->errors()->all()) {
// Stop doing further validations
return;
}
$this->v = $validator;
$this->next();
});
}
/**
* Add custom post-validation rules
*/
protected function next()
{
}
}
The next step is to create your Trait which will provide the way to validate your inputs thanks to the current validator instance and handle the correct error message you want to display :
<?php
namespace App\Custom\Validation;
trait CustomUserValidations
{
protected function validateUserEmailValidity($emailField)
{
$email = $this->input($emailField);
$user = \App\User::where('email', $email)->first();
if (! $user) {
return $this->v->errors()->add($emailField, 'Email not found');
}
if (! $user->valid_email) {
return $this->v->errors()->add($emailField, 'Email not valid');
}
// MORE VALIDATION POSSIBLE HERE
// YOU CAN ADD AS MORE AS YOU WANT
// ...
}
}
Finally, do not forget to extend your MyCustomFormRequest. For example, after your php artisan make:request CreateUserRequest, here's the easy way to do so :
<?php
namespace App\Http\Requests;
use App\Custom\Validation\MyCustomFormRequest;
use App\Custom\Validation\CustomUserValidations;
class CreateUserRequest extends MyCustomFormRequest
{
use CustomUserValidations;
/**
* Add custom post-validation rules
*/
public function next()
{
$this->validateUserEmailValidity('email');
}
/**
* 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 [
'email' => 'bail|required|email|max:255|unique:users',
'password' => 'bail|required',
'name' => 'bail|required|max:255',
'first_name' => 'bail|required|max:255',
];
}
}
I hope that you'll find your way in what I suggest.
If you are using Laravel 8 and would like to display different error messages for a specific validation, follow the steps below.
I am going to create a validation rule that checks if a field is a valid email or a valid phone number. It will also return different error messages.
Make a custom validtion rule like
php artisan make:rule EmailOrPhone
Navigate to the created file in Rules Folder ie Root->App->Rules->EmailOrPhone.php
Paste the following code
<?php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class EmailOrPhone implements Rule
{
public $error_message;
public function __construct()
{
}
public function passes($attribute, $value)
{
$value = trim($value);
if (is_numeric($value)){
if (strlen($value) != 10){
$this->error_message = "Phone number must contain 10 digits";
return false;
}else if (!Str::startsWith($value, '0')){
$this->error_message = "Phone number must start with 0";
return false;
}else{
return true;
}
}else{
$validator = Validator::make(['email' => $value],[
'email' => 'required|email'
]);
if($validator->passes()){
return true;
}else{
$this->error_message = "Please provide a valid email address";
return false;
}
}
}
public function message()
{
return $this->error_message;
}
}
You can now use the custom validation in your validator like
return Validator::make($data, [
'firstname' => ['required', 'string', 'max:255'],
'lastname' => ['required', 'string', 'max:255'],
'email_phone' => ['required', 'string', 'max:255', new EmailOrPhone()],
'password' => ['required', 'string', 'confirmed'],
]);
Poor handling of custom validation rules is why I ditched laravel (well, it was one of many reasons, but it was the straw that broke the camel's back, so to speak). But anyway, I have a three part answer for you: a reason why you don't want to do this in this specific case, a quick general overview of the mess you have to deal with, and then the answer to your question in case you still want to do it.
Important security concern
Best security practices for managing logins dictate that you should always return one generic error message for login problems. The quintessential counter-example would be if you returned "That email is not registered with our system" for an email-not-found and "Wrong password" for a correct email with the wrong password. In the case where you give separate validation messages, you give potential attackers additional information about how to more effectively direct their attacks. As a result, all login-related issues should return a generic validation message, regardless of the underlying cause, something to the effect of "Invalid email/password combination". The same is true for password recovery forms, which often say something like, "Password recovery instructions have been sent to that email, if it is present in our system". Otherwise you give attackers (and others) a way to know what email addresses are registered with your system, and that can expose additional attack vectors. So in this particular case, one validation message is what you want.
The trouble with laravel
The issue you are running into is that laravel validators simply return true or false to denote whether or not the rule is met. Error messages are handled separately. You specifically cannot specify the validator error message from inside your validator logic. I know. It's ridiculous, and poorly planned. All you can do is return true or false. You don't have access to anything else to help you, so your pseudo code isn't going to do it.
The (ugly) answer
The simplest way to create your own validation messages is to create your own validator. That looks something like this (inside your controller):
$validator = Validator::make($input, $rules, $messages);
You would still have to create your validator on boot (your Valiator::Extend call. Then you can specify the $rules normally by passing them in to your custom validator. Finally, you can specify your messages. Something like this, overall (inside your controller):
public function login( Request $request )
{
$rules = [
'email' => 'bail|required|checkEmailPresenceAndValidity'
]
$messages = [
'checkEmailPresenceAndValidity' => 'Invalid email.',
];
$validator = Validator::make($request->all(), $rules, $messages);
}
(I don't remember if you have to specify each rule in your $messages array. I don't think so). Of course, even this isn't very awesome, because what you pass for $messages is simply an array of strings (and that is all it is allowed to be). As a result, you still can't have this error message easily change according to user input. This all happens before your validator runs too. Your goal is to have the validation message change depending on the validation results, however laravel forces you to build the messages first. As a result, to really do what you want to do, you have to adjust the actual flow of the system, which isn't very awesome.
A solution would be to have a method in your controller that calculates whether or not your custom validation rule is met. It would do this before you make your validator so that you can send an appropriate message to the validator you build. Then, when you create the validation rule, you can also bind it to the results of your validation calculator, so long as you move your rule definition inside of your controller. You just have to make sure and not accidentally call things out of order. You also have to keep in mind that this requires moving your validation logic outside of the validators, which is fairly hacky. Unfortunately, I'm 95% sure there really isn't any other way to do this.
I've got some example code below. It definitely has some draw backs: your rule is no longer global (it is defined in the controller), the validation logic moves out of the validator (which violates the principle of least astonishment), and you will have to come up with an in-object caching scheme (which isn't hard) to make sure you don't execute your query twice, since the validation logic is called twice. To reiterate, it is definitely hacky, but I'm fairly certain that this is the only way to do what you want to do with laravel. There might be better ways to organize this, but this should at least give you an idea of what you need to make happen.
<?php
namespace App\Http\Controllers;
use User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
public function __construct() {
Validator::extend('checkEmailPresenceAndValidity', function ($attribute, $value, $parameters, $validator) {
return $this->checkLogin( $value ) === true ? true : false;
});
}
public function checkLogin( $email ) {
$user = User::where('email', $email)->first();
// Email has not been found
if (! $user) {
return 'not found';
}
// Email has not been validated
if (! $user->valid_email) {
return 'invalid';
}
return true;
}
public function login( Request $request ) {
$rules = [
'email' => 'bail|required|checkEmailPresenceAndValidity'
]
$hasError = $this->checkLogin( $request->email );
if ( $hasError === 'not found' )
$message = "That email wasn't found";
elseif ( $hasError === 'invalid' )
$message = "That is an invalid email";
else
$message = "Something was wrong with your request";
$messages = [
'checkEmailPresenceAndValidity' => $message,
];
$validator = Validator::make($request->all(), $rules, $messages);
if ($validator->fails()) {
// do something and redirect/exit
}
// process successful form here
}
}
Also, it is worth a quick note that this implementation relies on $this support for closures, which (I believe) was added in PHP 5.4. If you are on an old version of PHP you'll have to provide $this to the closure with use.
Edit to rant
What it really boils down to is that the laravel validation system is designed to be very granular. Each validation rule is specifically only supposed to validate one thing. As a result, the validation message for a given validator should never have to be changed, hence why $messages (when you build your own validator) only accepts plain strings.
In general granularity is a good thing in application design, and something that proper implementation of SOLID principles strive for. However, this particular implementation drives me crazy. My general programming philosophy is that a good implementation should make the most common uses-cases very easy, and then get out of your way for the less-common use-cases. In this cases the architecture of laravel makes the most common use-cases easy but the less common use-cases almost impossible. I'm not okay with that trade off. My general impression of Laravel was that it works great as long as you need to do things the laravel way, but if you have to step out of the box for any reason it is going to actively make your life more difficult. In your case the best answer is to probably just step right back inside that box, i.e. make two validators even if it means making a redundant query. The actual impact on your application performance likely will not matter at all, but the hit you will take to your long-term maintainability to get laravel to behave the way you want it will be quite large.
Alternatively to the other proposals, I think you could also call Validator::replacer('yourRule', function()) in addition to Validator::extend('yourRule', function(...)) and keep track of what causes validation failures in the service provider class you're extending the validator from. This way, you are be able to completely replace the default error message with another one.
According to docs, replacer() is meant for making placeholder replacements in the error message before it is being returned, so while this is not strictly that case, it is close enough. Of course, it's kind of an ugly(ish) workaround, but it will probably work (at least it seems to work for me, at a first glance).
One thing to keep in mind though is that you'll probably have to keep track of these failure causes in an array if you want to avoid automatically returning same message for all fields that failed your custom validation rule.
Where have you found the error messages for the size validation?
I looked up the validation rules in the
Illuminate\Validation\ConcernsValidatesAttributes trait and all functions return a bool value (also the size validation).
protected function validateSize($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'size');
return $this->getSize($attribute, $value) == $parameters[0];
}
What you have found belongs to this part:
$keys = ["{$attribute}.{$lowerRule}", $lowerRule];
In this case it's only for formatting the the output by setting a lowerRule value, that laravel handles in special cases, like the size validation:
// If the rule being validated is a "size" rule, we will need to gather the
// specific error message for the type of attribute being validated such
// as a number, file or string which all have different message types.
elseif (in_array($rule, $this->sizeRules)) {
return $this->getSizeMessage($attribute, $rule);
}
So as long as validation rules have to return a bool value there is no way to return more than one error message. Otherwise you have to rewrite some party of the validation rules.
An approach for your problem with the validation you could use the exists validation:
public function rules()
{
return [
'email' => ['bail', 'required', Rule::exists('users')->where(function($query) {
return $query->where('valid_email', 1);
})]
];
}
So you would need 2 exists validation rules. I would suggest to use the existing one from laravel to check if the email is set and a custom one to check if the account is validated.
I'm learning Laravel 5 and trying to validate if an email exists in database yet then add some custom message if it fails. I found the After Validation Hook in Laravel's documentation
$validator = Validator::make(...);
$validator->after(function($validator) use ($email) {
if (emailExist($email)) {
$validator->errors()->add('email', 'This email has been used!');
}
});
if ($validator->fails()) {
return redirect('somewhere')
->withErrors($validator);
}
but I don't really understand what this is. Because I can simply do this:
//as above
if (emailExist($email)) {
$validator->errors()->add('email', 'This email has been used!');
}
//redirect as above
It still outputs the same result. When should I use the 1st one to validate something instead of the 2nd one?
The point of the first method is just to keep everything contained inside of that Validator object to make it more reusable.
Yes, in your case it does the exact same thing. But imagine if you wanted to validate multiple items.
foreach ($inputs as $input) {
$validator->setData($input);
if ($validator->fails()) { ... }
}
In your case you will have to add that "if" check into the loop. Now imagine having to run this validation in many different places (multiple controllers, maybe a console script). Now you have this if statement in 3 different files, and next time you go to modify it you have 3x the amount of work, and maybe you forget to change it in one place...
I can't think of many use cases for this but that is the basic idea behind it.
By the way there is a validation rule called exists that will probably handle your emailExist() method
$rules = [
'email' => 'exists:users,email',
];
http://laravel.com/docs/5.1/validation#rule-exists
There may be many scenarios where you may feel it's requirement.
Just assume that you are trying to build REST api for a project. And you have decided that update request method will not have any required rule validation for any field in request (as there maybe many parameters and you do not want to pass them all just to change one column or maybe you do not have all the columns because you aren't allowed access to it) .
So how will you handle this validation in UpdatePostRequest.php class where you have put all the validation rules in rules() method as given in code.
Further more there may be requirement that sum of values of two or more request fields should be greater or less than some threshold quantity. Then what?
I agree that you can just check it in controller and redirect it from there but wouldn't it defeat the purpose of creating a dedicated request class if we were to do these checks in controllers.
What I feel is controllers should be clean and should not have multiple exit points based on validation. These small validation checks can be handled in request class itself by creating a new Rule or extending your own custom validation or creating after validation hooks and all of them have their unique usage in Laravel.
Therefore what you may want to to do here is create a validation hook where it's assigned is to check whether request is empty or not like the example given below
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (empty($this->toArray())) {
$validator->errors()->add('body', 'Request body cannot be empty');
}
if (!$this->validateCaptcha()) {
$validator->errors()->add('g-recaptcha-response', 'invalid');
}
});
}
And here is the full example for it.
<?php
namespace App\Http\Requests\Posts;
use App\Helpers\General\Tables;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdatePostRequest extends FormRequest
{
public function authorize()
{
return auth()->user()->can('update-post', $this);
}
public function rules()
{
return [
'name' => ['string', 'min:3', 'max:255'],
'email' => ['string', 'email', 'min:3', 'max:255'],
'post_data' => ['string', 'min:3', 'max:255'],
];
}
public function withValidator($validator)
{
$validator->after(function ($validator) {
if (empty($this->toArray())) {
$validator->errors()->add('body', 'Request body cannot be empty');
}
});
}
}
Thanks..
passedValidation method will trigger if the validation passes in FormRequest class. Actually this method is rename of afterValidation method. See: method rename Commit
So you can do like
class RegistrationRequest extends FormRequest
{
/**
* Handle a passed validation attempt.
*
* #return void
*/
protected function passedValidation()
{
$this->merge(
[
'password' => bcrypt($this->password),
]
);
}
}
Is it possible to conditionally set a custom language file (e.g. resources/lang/en/validation_ajax.php) for a validation request? Just to be clear, I don't want to change the app language, just use another set of messages depending on the request origin.
When I make an ajax validation call I want to use different messages since I'm showing the error messages below the field itself. So there's no need to show the field name (label) again.
I know you can define labels on 'attributes' => [] but it's not worth the effort since I have so many fields in several languages.
I'm using a FormRequest (there's no manual call on the Controller just a type hint).
You can override the messages() method for a specific request (let's say login request). Let me show you: At first place, you need yo create a new custom Form Request, here we will define a custom message for email.required rule:
<?php namespace App\MyPackage\Requests;
use App\Http\Requests\Request;
class LoginRequest extends Request {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
public function messages()
{
return [
'email.required' => 'how about the email?',
];
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'email' => ['required', 'email'],
'password' => ['required', 'confirmed']
];
}
}
Only email.required rule message will be override. For password it will display the default message set at validation.php file.
Now, apply the form request at your controller function like a type hint:
class LoginController{
public function validateCredentials(LoginRequest $request){
// do tasks here if rules were success
}
}
And that is all. The messages() method is useful if you need are creating custom packages and you want to add/edit validation messages.
Update
If you need to carry the bag of messages on into your package's lang file then you can make the following changes:
At your package create your custom lang file:
MyPackage/resources/lang/en/validation.php
Add the messages keeping the same array's structure as project/resources/lang/en/validation.php file:
<?php
return [
'email' => [
'required' => 'how about the email?',
'email' => 'how about the email format?',
],
];
Finally, at your messages() method call the lang's line of your package respectively:
public function messages(){
return [
'email.required' => trans('myPackage::validation.email.required'),
'email.emial' => trans('myPackage::validation.email.valid'),
];
}