Laravel Check if Uploaded File Is Actula Type

Validation

  • Introduction
  • Validation Quickstart
    • Defining The Routes
    • Creating The Controller
    • Writing The Validation Logic
    • Displaying The Validation Errors
    • Repopulating Forms
    • A Note On Optional Fields
  • Course Asking Validation
    • Creating Course Requests
    • Authorizing Form Requests
    • Customizing The Error Messages
    • Preparing Input For Validation
  • Manually Creating Validators
    • Automatic Redirection
    • Named Error Numberless
    • Customizing The Error Messages
    • Later on Validation Claw
  • Working With Validated Input
  • Working With Error Letters
    • Specifying Custom Messages In Linguistic communication Files
    • Specifying Attributes In Language Files
    • Specifying Values In Language Files
  • Available Validation Rules
  • Conditionally Adding Rules
  • Validating Arrays
    • Validating Nested Array Input
    • Fault Bulletin Indexes & Positions
  • Validating Passwords
  • Custom Validation Rules
    • Using Rule Objects
    • Using Closures
    • Implicit Rules

Introduction

Laravel provides several different approaches to validate your application's incoming data. It is near common to employ the validate method available on all incoming HTTP requests. Yet, we volition discuss other approaches to validation too.

Laravel includes a wide multifariousness of convenient validation rules that you may utilise to data, even providing the ability to validate if values are unique in a given database tabular array. We'll cover each of these validation rules in detail and so that you are familiar with all of Laravel's validation features.

Validation Quickstart

To learn about Laravel's powerful validation features, let's look at a complete instance of validating a course and displaying the mistake messages back to the user. By reading this loftier-level overview, you lot'll be able to proceeds a skilful general understanding of how to validate incoming request information using Laravel:

Defining The Routes

First, let's presume we have the following routes defined in our routes/web.php file:

                                        

utilise App\Http\Controllers\ PostController ;

Route :: become ( ' /postal service/create ' , [ PostController :: class , ' create ' ]);

Route :: post ( ' /post ' , [ PostController :: class , ' store ' ]);

The Go route volition display a form for the user to create a new blog post, while the POST route volition store the new blog mail in the database.

Creating The Controller

Next, let'south take a look at a simple controller that handles incoming requests to these routes. Nosotros'll leave the store method empty for now:

                                        

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\ Controller ;

utilise Illuminate\Http\ Request ;

course PostController extends Controller

{

/**

* Show the form to create a new web log post.

*

* @return \ Illuminate \ View \ View

*/

public office create ()

{

render view ( ' mail.create ' );

}

/**

* Store a new web log postal service.

*

* @param \ Illuminate \ Http \ Request $request

* @return \ Illuminate \ Http \ Response

*/

public function store ( Request $request )

{

// Validate and store the blog postal service...

}

}

Writing The Validation Logic

At present we are ready to fill up in our store method with the logic to validate the new weblog post. To practice this, we will use the validate method provided by the Illuminate\Http\Request object. If the validation rules laissez passer, your code will keep executing normally; however, if validation fails, an Illuminate\Validation\ValidationException exception will exist thrown and the proper fault response will automatically be sent back to the user.

If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation mistake messages will be returned.

To go a better understanding of the validate method, permit'due south jump dorsum into the store method:

                                        

/**

* Store a new weblog post.

*

* @param \ Illuminate \ Http \ Request $asking

* @return \ Illuminate \ Http \ Response

*/

public office store ( Request $request )

{

$validated = $request -> validate ([

' championship ' => ' required|unique:posts|max:255 ' ,

' body ' => ' required ' ,

]);

// The blog mail service is valid...

}

As you can see, the validation rules are passed into the validate method. Don't worry - all available validation rules are documented. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally.

Alternatively, validation rules may exist specified equally arrays of rules instead of a unmarried | delimited string:

                                        

$validatedData = $request -> validate ([

' title ' => [ ' required ' , ' unique:posts ' , ' max:255 ' ],

' body ' => [ ' required ' ],

]);

In addition, yous may utilize the validateWithBag method to validate a request and store whatsoever fault messages within a named fault handbag:

                                        

$validatedData = $request -> validateWithBag ( ' postal service ' , [

' title ' => [ ' required ' , ' unique:posts ' , ' max:255 ' ],

' body ' => [ ' required ' ],

]);

Stopping On Commencement Validation Failure

Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute:

                                        

$request -> validate ([

' championship ' => ' bail|required|unique:posts|max:255 ' ,

' body ' => ' required ' ,

]);

In this instance, if the unique rule on the championship attribute fails, the max dominion volition non be checked. Rules volition exist validated in the order they are assigned.

A Note On Nested Attributes

If the incoming HTTP asking contains "nested" field data, you may specify these fields in your validation rules using "dot" syntax:

                                        

$request -> validate ([

' title ' => ' required|unique:posts|max:255 ' ,

' author.proper name ' => ' required ' ,

' author.clarification ' => ' required ' ,

]);

On the other hand, if your field name contains a literal menses, y'all tin explicitly prevent this from being interpreted every bit "dot" syntax by escaping the flow with a backslash:

                                        

$request -> validate ([

' title ' => ' required|unique:posts|max:255 ' ,

' v1\.0 ' => ' required ' ,

]);

Displaying The Validation Errors

And then, what if the incoming asking fields do non pass the given validation rules? As mentioned previously, Laravel volition automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session.

An $errors variable is shared with all of your application'due south views by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is practical an $errors variable will e'er be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The $errors variable will be an case of Illuminate\Support\MessageBag. For more than information on working with this object, bank check out its documentation.

And then, in our example, the user will be redirected to our controller's create method when validation fails, allowing us to display the fault messages in the view:

                                        

<!-- /resources/views/post/create.blade.php -->

< h1 > Create Post </ h1 >

@if ( $errors -> any ())

< div class = " alarm alert-danger " >

< ul >

@foreach ( $errors -> all () as $error )

< li >{{ $fault }}</ li >

@endforeach

</ ul >

</ div >

@endif

<!-- Create Post Form -->

Customizing The Error Messages

Laravel'due south built-in validation rules each has an error message that is located in your application's lang/en/validation.php file. Within this file, yous will discover a translation entry for each validation rule. You are complimentary to change or modify these letters based on the needs of your application.

In addition, y'all may copy this file to another translation linguistic communication directory to interpret the messages for your application's linguistic communication. To learn more than almost Laravel localization, cheque out the complete localization documentation.

XHR Requests & Validation

In this case, we used a traditional course to send information to the application. Nevertheless, many applications receive XHR requests from a JavaScript powered frontend. When using the validate method during an XHR request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

The @error Directive

You lot may use the @mistake Blade directive to quickly determine if validation error messages exist for a given attribute. Within an @error directive, you may echo the $bulletin variable to display the fault message:

                                        

<!-- /resources/views/post/create.blade.php -->

< label for = " title " > Post Title </ characterization >

< input id = " title "

type = " text "

name = " title "

class = " @fault ( ' title ' ) is-invalid @enderror " >

@error ( ' title ' )

< div grade = " alarm alert-danger " >{{ $bulletin }}</ div >

@enderror

If you are using named mistake bags, you may laissez passer the proper name of the fault pocketbook as the 2nd argument to the @error directive:

                                        

< input ... class = " @fault ( ' title ' , ' post ' ) is-invalid @enderror " >

Repopulating Forms

When Laravel generates a redirect response due to a validation mistake, the framework volition automatically flash all of the request'southward input to the session. This is done so that you may conveniently access the input during the adjacent asking and repopulate the form that the user attempted to submit.

To retrieve flashed input from the previous request, invoke the onetime method on an instance of Illuminate\Http\Asking. The old method will pull the previously flashed input data from the session:

                                        

$title = $asking -> quondam ( ' title ' );

Laravel also provides a global onetime helper. If you are displaying former input within a Blade template, information technology is more than convenient to utilise the old helper to repopulate the form. If no old input exists for the given field, goose egg volition be returned:

                                        

< input type = " text " name = " title " value = " {{ old ( ' title ' ) }} " >

A Note On Optional Fields

By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application'due south global middleware stack. These middleware are listed in the stack past the App\Http\Kernel course. Because of this, you will often need to mark your "optional" request fields as nullable if yous do not want the validator to consider null values equally invalid. For example:

                                        

$request -> validate ([

' championship ' => ' required|unique:posts|max:255 ' ,

' body ' => ' required ' ,

' publish_at ' => ' nullable|appointment ' ,

]);

In this example, nosotros are specifying that the publish_at field may exist either naught or a valid date representation. If the nullable modifier is not added to the rule definition, the validator would consider null an invalid date.

Form Asking Validation

Creating Form Requests

For more complex validation scenarios, you may wish to create a "form request". Class requests are custom asking classes that encapsulate their own validation and authority logic. To create a form asking grade, you may use the make:request Artisan CLI control:

                                        

php artisan make:request StorePostRequest

The generated grade request course will be placed in the app/Http/Requests directory. If this directory does non exist, it will be created when y'all run the make:request command. Each class asking generated by Laravel has two methods: authorize and rules.

Equally you might take guessed, the authorize method is responsible for determining if the currently authenticated user can perform the action represented by the request, while the rules method returns the validation rules that should apply to the request's data:

                                        

/**

* Get the validation rules that apply to the request.

*

* @render array

*/

public function rules ()

{

return [

' title ' => ' required|unique:posts|max:255 ' ,

' body ' => ' required ' ,

];

}

{tip} Y'all may blazon-hint any dependencies you require within the rules method'southward signature. They will automatically be resolved via the Laravel service container.

So, how are the validation rules evaluated? All you need to practice is blazon-hint the asking on your controller method. The incoming form request is validated before the controller method is called, meaning yous practice non need to clutter your controller with whatsoever validation logic:

                                        

/**

* Store a new blog post.

*

* @param \ App \ Http \ Requests \ StorePostRequest $request

* @return Illuminate \ Http \ Response

*/

public function store ( StorePostRequest $asking )

{

// The incoming request is valid...

// Call back the validated input data...

$validated = $request -> validated ();

// Retrieve a portion of the validated input data...

$validated = $request -> safe () -> only ([ ' name ' , ' email ' ]);

$validated = $request -> safe () -> except ([ ' name ' , ' email ' ]);

}

If validation fails, a redirect response will be generated to send the user back to their previous location. The errors will besides be flashed to the session and then they are available for display. If the request was an XHR asking, an HTTP response with a 422 condition code will be returned to the user including a JSON representation of the validation errors.

Adding Later Hooks To Class Requests

If you lot would like to add an "after" validation claw to a class request, you may employ the withValidator method. This method receives the fully synthetic validator, assuasive you to call whatsoever of its methods before the validation rules are really evaluated:

                                        

/**

* Configure the validator instance.

*

* @param \ Illuminate \ Validation \ Validator $validator

* @return void

*/

public function withValidator ( $validator )

{

$validator -> after ( office ( $validator ) {

if ( $this -> somethingElseIsInvalid ()) {

$validator -> errors () -> add ( ' field ' , ' Something is wrong with this field! ' );

}

});

}

Stopping On Start Validation Failure Attribute

Past adding a stopOnFirstFailure property to your request class, you may inform the validator that it should stop validating all attributes in one case a single validation failure has occurred:

                                        

/**

* Indicates if the validator should stop on the first rule failure.

*

* @var bool

*/

protected $stopOnFirstFailure = true ;

Customizing The Redirect Location

As previously discussed, a redirect response will be generated to transport the user back to their previous location when form asking validation fails. However, you are free to customize this behavior. To practice and so, define a $redirect property on your course request:

                                        

/**

* The URI that users should be redirected to if validation fails.

*

* @var string

*/

protected $redirect = ' /dashboard ' ;

Or, if yous would like to redirect users to a named route, you may ascertain a $redirectRoute belongings instead:

                                        

/**

* The route that users should be redirected to if validation fails.

*

* @var string

*/

protected $redirectRoute = ' dashboard ' ;

Authorizing Course Requests

The form request class also contains an authorize method. Inside this method, you may determine if the authenticated user actually has the say-so to update a given resources. For example, yous may determine if a user really owns a web log comment they are attempting to update. Well-nigh likely, you will interact with your authority gates and policies within this method:

                                        

employ App\Models\ Comment ;

/**

* Make up one's mind if the user is authorized to make this request.

*

* @return bool

*/

public function authorize ()

{

$comment = Comment :: notice ( $this -> route ( ' comment ' ));

render $comment && $this -> user () -> can ( ' update ' , $comment );

}

Since all form requests extend the base Laravel request course, we may use the user method to access the currently authenticated user. Too, notation the call to the route method in the instance to a higher place. This method grants yous access to the URI parameters defined on the route being called, such as the {annotate} parameter in the case below:

                                        

Route :: post ( ' /comment/{comment} ' );

Therefore, if your application is taking advantage of route model binding, your code may be made fifty-fifty more than succinct by accessing the resolved model every bit a belongings of the request:

                                        

render $this -> user () -> tin can ( ' update ' , $this ->comment );

If the authorize method returns false, an HTTP response with a 403 status code will automatically be returned and your controller method will not execute.

If you plan to handle say-so logic for the asking in another office of your application, you may merely return true from the qualify method:

                                        

/**

* Determine if the user is authorized to make this request.

*

* @return bool

*/

public role authorize ()

{

return true ;

}

{tip} You may type-hint any dependencies yous need inside the qualify method's signature. They volition automatically exist resolved via the Laravel service container.

Customizing The Fault Messages

You lot may customize the fault letters used past the form asking by overriding the messages method. This method should return an assortment of attribute / rule pairs and their respective mistake messages:

                                        

/**

* Become the error letters for the defined validation rules.

*

* @return array

*/

public part messages ()

{

return [

' title.required ' => ' A title is required ' ,

' body.required ' => ' A message is required ' ,

];

}

Customizing The Validation Attributes

Many of Laravel's congenital-in validation rule mistake letters contain an :attribute placeholder. If you would like the :attribute placeholder of your validation message to exist replaced with a custom attribute name, you lot may specify the custom names by overriding the attributes method. This method should render an array of attribute / proper name pairs:

                                        

/**

* Go custom attributes for validator errors.

*

* @render assortment

*/

public part attributes ()

{

return [

' email ' => ' email accost ' ,

];

}

Preparing Input For Validation

If you need to prepare or sanitize whatever data from the request before you apply your validation rules, y'all may use the prepareForValidation method:

                                        

utilize Illuminate\Support\ Str ;

/**

* Prepare the data for validation.

*

* @render void

*/

protected function prepareForValidation ()

{

$this -> merge ([

' slug ' => Str :: slug ( $this ->slug ),

]);

}

Manually Creating Validators

If you do not want to employ the validate method on the request, you may create a validator instance manually using the Validator facade. The make method on the facade generates a new validator instance:

                                        

<?php

namespace App\Http\Controllers;

apply App\Http\Controllers\ Controller ;

apply Illuminate\Http\ Request ;

use Illuminate\Support\Facades\ Validator ;

class PostController extends Controller

{

/**

* Store a new weblog post.

*

* @param Request $request

* @return Response

*/

public function store ( Asking $request )

{

$validator = Validator :: make ( $request -> all (), [

' championship ' => ' required|unique:posts|max:255 ' ,

' trunk ' => ' required ' ,

]);

if ( $validator -> fails ()) {

render redirect ( ' post/create ' )

-> withErrors ( $validator )

-> withInput ();

}

// Call back the validated input...

$validated = $validator -> validated ();

// Retrieve a portion of the validated input...

$validated = $validator -> prophylactic () -> only ([ ' name ' , ' e-mail ' ]);

$validated = $validator -> safe () -> except ([ ' proper noun ' , ' electronic mail ' ]);

// Shop the blog post...

}

}

The kickoff argument passed to the make method is the data under validation. The second argument is an assortment of the validation rules that should be practical to the data.

Later determining whether the asking validation failed, you may utilize the withErrors method to flash the error letters to the session. When using this method, the $errors variable will automatically be shared with your views subsequently redirection, allowing you lot to easily display them back to the user. The withErrors method accepts a validator, a MessageBag, or a PHP array.

Stopping On First Validation Failure

The stopOnFirstFailure method volition inform the validator that it should stop validating all attributes in one case a unmarried validation failure has occurred:

                                        

if ( $validator -> stopOnFirstFailure () -> fails ()) {

// ...

}

Automated Redirection

If y'all would like to create a validator example manually only still have advantage of the automated redirection offered by the HTTP request'south validate method, you may call the validate method on an existing validator instance. If validation fails, the user will automatically be redirected or, in the case of an XHR asking, a JSON response will be returned:

                                        

Validator :: make ( $asking -> all (), [

' title ' => ' required|unique:posts|max:255 ' ,

' trunk ' => ' required ' ,

]) -> validate ();

Yous may use the validateWithBag method to store the error messages in a named mistake handbag if validation fails:

                                        

Validator :: brand ( $asking -> all (), [

' title ' => ' required|unique:posts|max:255 ' ,

' body ' => ' required ' ,

]) -> validateWithBag ( ' mail service ' );

Named Error Numberless

If you have multiple forms on a single folio, yous may wish to name the MessageBag containing the validation errors, allowing you to retrieve the error messages for a specific grade. To reach this, laissez passer a name every bit the second argument to withErrors:

                                        

return redirect ( ' register ' ) -> withErrors ( $validator , ' login ' );

You may then access the named MessageBag instance from the $errors variable:

                                        

{{ $errors ->login-> first ( ' email ' ) }}

Customizing The Error Messages

If needed, you may provide custom error messages that a validator example should use instead of the default error messages provided by Laravel. There are several ways to specify custom letters. First, you may pass the custom messages as the tertiary statement to the Validator::make method:

                                        

$validator = Validator :: brand ( $input , $rules , $messages = [

' required ' => ' The :attribute field is required. ' ,

]);

In this instance, the :attribute placeholder will be replaced by the actual name of the field under validation. You may also utilize other placeholders in validation messages. For example:

                                        

$messages = [

' same ' => ' The :attribute and :other must match. ' ,

' size ' => ' The :attribute must be exactly :size. ' ,

' between ' => ' The :attribute value :input is non between :min - :max. ' ,

' in ' => ' The :attribute must be one of the following types: :values ' ,

];

Specifying A Custom Message For A Given Attribute

Sometimes you may wish to specify a custom error bulletin just for a specific aspect. You may exercise so using "dot" note. Specify the attribute'due south proper noun first, followed by the rule:

                                        

$letters = [

' e-mail.required ' => ' We need to know your email address! ' ,

];

Specifying Custom Aspect Values

Many of Laravel'south congenital-in error messages include an :attribute placeholder that is replaced with the name of the field or aspect under validation. To customize the values used to replace these placeholders for specific fields, y'all may pass an assortment of custom attributes equally the fourth argument to the Validator::brand method:

                                        

$validator = Validator :: make ( $input , $rules , $messages , [

' e-mail ' => ' email address ' ,

]);

After Validation Hook

You may also adhere callbacks to be run subsequently validation is completed. This allows you to easily perform further validation and even add together more error messages to the message drove. To get started, call the later on method on a validator instance:

                                        

$validator = Validator :: make ( ... );

$validator -> afterward ( function ( $validator ) {

if ( $this -> somethingElseIsInvalid ()) {

$validator -> errors () -> add (

' field ' , ' Something is incorrect with this field! '

);

}

});

if ( $validator -> fails ()) {

//

}

Working With Validated Input

After validating incoming request information using a grade request or a manually created validator instance, yous may wish to retrieve the incoming request information that actually underwent validation. This can be accomplished in several ways. First, you may phone call the validated method on a course request or validator case. This method returns an array of the data that was validated:

                                        

$validated = $request -> validated ();

$validated = $validator -> validated ();

Alternatively, yous may call the safe method on a course request or validator instance. This method returns an instance of Illuminate\Support\ValidatedInput. This object exposes only, except, and all methods to call up a subset of the validated data or the entire array of validated data:

                                        

$validated = $request -> safe () -> but ([ ' name ' , ' email ' ]);

$validated = $request -> safe () -> except ([ ' proper name ' , ' email ' ]);

$validated = $request -> prophylactic () -> all ();

In addition, the Illuminate\Support\ValidatedInput instance may be iterated over and accessed similar an array:

                                        

// Validated data may exist iterated...

foreach ( $request -> safe () as $central => $value ) {

//

}

// Validated information may be accessed as an array...

$validated = $asking -> safe ();

$email = $validated [ ' email ' ];

If you would like to add together additional fields to the validated data, you may phone call the merge method:

                                        

$validated = $asking -> prophylactic () -> merge ([ ' name ' => ' Taylor Otwell ' ]);

If y'all would similar to retrieve the validated information every bit a collection instance, you may telephone call the collect method:

                                        

$collection = $request -> safe () -> collect ();

Working With Mistake Messages

After calling the errors method on a Validator example, you will receive an Illuminate\Support\MessageBag instance, which has a variety of user-friendly methods for working with error messages. The $errors variable that is automatically made available to all views is also an case of the MessageBag form.

Retrieving The First Error Bulletin For A Field

To recollect the start fault message for a given field, use the first method:

                                        

$errors = $validator -> errors ();

echo $errors -> first ( ' e-mail ' );

Retrieving All Error Messages For A Field

If you need to retrieve an array of all the messages for a given field, utilize the get method:

                                        

foreach ( $errors -> become ( ' email ' ) equally $bulletin ) {

//

}

If you are validating an array class field, you may recall all of the letters for each of the array elements using the * character:

                                        

foreach ( $errors -> become ( ' attachments.* ' ) equally $message ) {

//

}

Retrieving All Error Messages For All Fields

To retrieve an array of all messages for all fields, use the all method:

                                        

foreach ( $errors -> all () as $message ) {

//

}

Determining If Messages Exist For A Field

The has method may be used to determine if whatsoever error messages be for a given field:

                                        

if ( $errors -> has ( ' e-mail ' )) {

//

}

Specifying Custom Messages In Language Files

Laravel's born validation rules each has an error message that is located in your awarding's lang/en/validation.php file. Within this file, you volition find a translation entry for each validation rule. Yous are free to change or modify these messages based on the needs of your application.

In improver, you lot may copy this file to some other translation language directory to translate the messages for your awarding's language. To learn more about Laravel localization, check out the consummate localization documentation.

Custom Messages For Specific Attributes

Yous may customize the fault messages used for specified aspect and dominion combinations within your application'due south validation linguistic communication files. To do and so, add together your bulletin customizations to the custom array of your application's lang/xx/validation.php linguistic communication file:

                                        

' custom ' => [

' email ' => [

' required ' => ' Nosotros need to know your email address! ' ,

' max ' => ' Your electronic mail address is too long! '

],

],

Specifying Attributes In Language Files

Many of Laravel's congenital-in fault messages include an :attribute placeholder that is replaced with the name of the field or aspect nether validation. If you would like the :attribute portion of your validation bulletin to be replaced with a custom value, y'all may specify the custom aspect name in the attributes array of your lang/xx/validation.php language file:

                                        

' attributes ' => [

' email ' => ' email accost ' ,

],

Specifying Values In Language Files

Some of Laravel's congenital-in validation rule error messages contain a :value placeholder that is replaced with the current value of the request attribute. However, you lot may occasionally need the :value portion of your validation message to be replaced with a custom representation of the value. For example, consider the post-obit dominion that specifies that a credit carte du jour number is required if the payment_type has a value of cc:

                                        

Validator :: make ( $request -> all (), [

' credit_card_number ' => ' required_if:payment_type,cc '

]);

If this validation rule fails, it will produce the following mistake message:

                                        

The credit card number field is required when payment type is cc.

Instead of displaying cc as the payment blazon value, you may specify a more convenient value representation in your lang/20/validation.php language file by defining a values array:

                                        

' values ' => [

' payment_type ' => [

' cc ' => ' credit card '

],

],

Subsequently defining this value, the validation rule volition produce the post-obit error message:

                                        

The credit menu number field is required when payment type is credit card.

Available Validation Rules

Below is a listing of all available validation rules and their function:

accepted

The field under validation must be "yeah", "on", 1, or true. This is useful for validating "Terms of Service" acceptance or similar fields.

accepted_if:anotherfield,value,...

The field under validation must be "yes", "on", ane, or true if another field under validation is equal to a specified value. This is useful for validating "Terms of Service" acceptance or similar fields.

active_url

The field under validation must have a valid A or AAAA tape according to the dns_get_record PHP role. The hostname of the provided URL is extracted using the parse_url PHP function before being passed to dns_get_record.

after:date

The field under validation must be a value after a given appointment. The dates volition exist passed into the strtotime PHP function in order to be converted to a valid DateTime example:

                                        

' start_date ' => ' required|date|subsequently:tomorrow '

Instead of passing a appointment cord to be evaluated past strtotime, you may specify another field to compare against the date:

                                        

' finish_date ' => ' required|date|subsequently:start_date '

after_or_equal:date

The field under validation must be a value later or equal to the given date. For more information, see the subsequently rule.

alpha

The field nether validation must exist entirely alphabetic characters.

alpha_dash

The field under validation may have alpha-numeric characters, likewise as dashes and underscores.

alpha_num

The field under validation must be entirely alpha-numeric characters.

array

The field under validation must exist a PHP array.

When additional values are provided to the array dominion, each key in the input array must be nowadays within the list of values provided to the rule. In the following case, the admin cardinal in the input array is invalid since it is non contained in the listing of values provided to the array dominion:

                                        

use Illuminate\Support\Facades\ Validator ;

$input = [

' user ' => [

' name ' => ' Taylor Otwell ' ,

' username ' => ' taylorotwell ' ,

' admin ' => true ,

],

];

Validator :: make ( $input , [

' user ' => ' assortment:username,locale ' ,

]);

In full general, you should always specify the array keys that are allowed to be present inside your array.

bail

Stop running validation rules for the field subsequently the first validation failure.

While the bail rule volition just cease validating a specific field when information technology encounters a validation failure, the stopOnFirstFailure method will inform the validator that it should cease validating all attributes once a single validation failure has occurred:

                                        

if ( $validator -> stopOnFirstFailure () -> fails ()) {

// ...

}

before:date

The field under validation must be a value preceding the given appointment. The dates volition be passed into the PHP strtotime function in order to exist converted into a valid DateTime instance. In addition, like the after rule, the proper noun of another field under validation may be supplied as the value of engagement.

before_or_equal:date

The field under validation must be a value preceding or equal to the given date. The dates will exist passed into the PHP strtotime function in society to be converted into a valid DateTime instance. In improver, similar the later on rule, the name of another field under validation may be supplied as the value of appointment.

betwixt:min,max

The field under validation must have a size betwixt the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion equally the size dominion.

boolean

The field under validation must be able to be cast every bit a boolean. Accustomed input are truthful, false, i, 0, "ane", and "0".

confirmed

The field under validation must accept a matching field of {field}_confirmation. For example, if the field under validation is password, a matching password_confirmation field must be present in the input.

current_password

The field under validation must match the authenticated user's password. You may specify an authentication baby-sit using the rule'southward offset parameter:

                                        

' password ' => ' current_password:api '

date

The field under validation must be a valid, non-relative engagement according to the strtotime PHP function.

date_equals:engagement

The field under validation must be equal to the given engagement. The dates volition exist passed into the PHP strtotime function in order to exist converted into a valid DateTime instance.

date_format:format

The field under validation must friction match the given format. Yous should employ either date or date_format when validating a field, not both. This validation dominion supports all formats supported by PHP's DateTime grade.

declined

The field under validation must be "no", "off", 0, or false.

declined_if:anotherfield,value,...

The field nether validation must be "no", "off", 0, or false if some other field under validation is equal to a specified value.

unlike:field

The field under validation must have a different value than field.

digits:value

The field under validation must be numeric and must have an verbal length of value.

digits_between:min,max

The field under validation must be numeric and must have a length between the given min and max.

dimensions

The file under validation must be an image coming together the dimension constraints as specified by the dominion'south parameters:

                                        

' avatar ' => ' dimensions:min_width=100,min_height=200 '

Available constraints are: min_width, max_width, min_height, max_height, width, height, ratio.

A ratio constraint should be represented every bit width divided by height. This tin can be specified either by a fraction similar 3/2 or a float like 1.5:

                                        

' avatar ' => ' dimensions:ratio=3/2 '

Since this rule requires several arguments, you may use the Rule::dimensions method to fluently construct the rule:

                                        

employ Illuminate\Support\Facades\ Validator ;

use Illuminate\Validation\ Rule ;

Validator :: make ( $information , [

' avatar ' => [

' required ' ,

Rule :: dimensions () -> maxWidth ( 1000 ) -> maxHeight ( 500 ) -> ratio ( 3 / ii ),

],

]);

distinct

When validating arrays, the field under validation must non accept any duplicate values:

                                        

' foo.*.id ' => ' singled-out '

Distinct uses loose variable comparisons past default. To use strict comparisons, you lot may add together the strict parameter to your validation rule definition:

                                        

' foo.*.id ' => ' singled-out:strict '

You lot may add ignore_case to the validation dominion'southward arguments to brand the rule ignore capitalization differences:

                                        

' foo.*.id ' => ' distinct:ignore_case '

email

The field under validation must be formatted equally an email accost. This validation rule utilizes the egulias/email-validator package for validating the email accost. By default, the RFCValidation validator is practical, but you can employ other validation styles as well:

                                        

' email ' => ' electronic mail:rfc,dns '

The case above volition apply the RFCValidation and DNSCheckValidation validations. Here's a full list of validation styles you tin can apply:

  • rfc: RFCValidation
  • strict: NoRFCWarningsValidation
  • dns: DNSCheckValidation
  • spoof: SpoofCheckValidation
  • filter: FilterEmailValidation

The filter validator, which uses PHP's filter_var function, ships with Laravel and was Laravel's default email validation behavior prior to Laravel version 5.8.

{note} The dns and spoof validators require the PHP intl extension.

ends_with:foo,bar,...

The field under validation must terminate with one of the given values.

enum

The Enum dominion is a grade based rule that validates whether the field nether validation contains a valid enum value. The Enum rule accepts the name of the enum equally its only constructor argument:

                                        

employ App\Enums\ ServerStatus ;

use Illuminate\Validation\Rules\ Enum ;

$request -> validate ([

' status ' => [ new Enum ( ServerStatus :: class )],

]);

{note} Enums are only available on PHP 8.1+.

exclude

The field nether validation will be excluded from the request data returned by the validate and validated methods.

exclude_if:anotherfield,value

The field under validation volition exist excluded from the request data returned by the validate and validated methods if the anotherfield field is equal to value.

If complex conditional exclusion logic is required, you may apply the Rule::excludeIf method. This method accepts a boolean or a closure. When given a closure, the closure should return true or false to betoken if the field under validation should be excluded:

                                        

use Illuminate\Support\Facades\ Validator ;

use Illuminate\Validation\ Dominion ;

Validator :: make ( $request -> all (), [

' role_id ' => Rule :: excludeIf ( $asking -> user () ->is_admin ),

]);

Validator :: make ( $asking -> all (), [

' role_id ' => Rule :: excludeIf ( fn () => $request -> user () ->is_admin ),

]);

exclude_unless:anotherfield,value

The field nether validation volition exist excluded from the request data returned by the validate and validated methods unless anotherfield's field is equal to value. If value is null (exclude_unless:proper name,zilch), the field nether validation will be excluded unless the comparison field is zilch or the comparison field is missing from the request data.

exclude_with:anotherfield

The field under validation volition be excluded from the request data returned by the validate and validated methods if the anotherfield field is present.

exclude_without:anotherfield

The field under validation volition be excluded from the request data returned past the validate and validated methods if the anotherfield field is not present.

exists:tabular array,column

The field nether validation must be in a given database table.

Bones Usage Of Exists Rule

                                        

' state ' => ' exists:states '

If the column option is non specified, the field name volition be used. And so, in this case, the rule will validate that the states database tabular array contains a record with a state column value matching the asking's country aspect value.

Specifying A Custom Column Proper noun

You may explicitly specify the database column name that should be used by the validation rule by placing it after the database table name:

                                        

' state ' => ' exists:states,abridgement '

Occasionally, you may demand to specify a specific database connection to be used for the exists query. You can accomplish this by prepending the connection name to the table name:

                                        

' email ' => ' exists:connection.staff,electronic mail '

Instead of specifying the table name directly, you lot may specify the Eloquent model which should be used to make up one's mind the table name:

                                        

' user_id ' => ' exists:App\Models\User,id '

If you would like to customize the query executed past the validation dominion, yous may utilise the Dominion class to fluently define the dominion. In this case, we'll besides specify the validation rules as an array instead of using the | grapheme to circumscribe them:

                                        

use Illuminate\Support\Facades\ Validator ;

use Illuminate\Validation\ Rule ;

Validator :: brand ( $data , [

' e-mail ' => [

' required ' ,

Rule :: exists ( ' staff ' ) -> where ( function ( $query ) {

render $query -> where ( ' account_id ' , 1 );

}),

],

]);

Y'all may explicitly specify the database column proper name that should exist used by the exists dominion generated past the Rule::exists method past providing the cavalcade name as the second argument to the exists method:

                                        

' state ' => Rule :: exists ( ' states ' , ' abridgement ' ),

file

The field nether validation must exist a successfully uploaded file.

filled

The field nether validation must not be empty when it is nowadays.

gt:field

The field under validation must be greater than the given field. The 2 fields must exist of the same blazon. Strings, numerics, arrays, and files are evaluated using the same conventions every bit the size rule.

gte:field

The field nether validation must be greater than or equal to the given field. The ii fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the same conventions every bit the size dominion.

prototype

The file nether validation must be an image (jpg, jpeg, png, bmp, gif, svg, or webp).

in:foo,bar,...

The field under validation must be included in the given list of values. Since this rule oft requires you to implode an assortment, the Rule::in method may be used to fluently construct the rule:

                                        

employ Illuminate\Support\Facades\ Validator ;

employ Illuminate\Validation\ Dominion ;

Validator :: brand ( $data , [

' zones ' => [

' required ' ,

Rule :: in ([ ' first-zone ' , ' second-zone ' ]),

],

]);

When the in dominion is combined with the array rule, each value in the input assortment must be present within the list of values provided to the in rule. In the following case, the LAS aerodrome lawmaking in the input array is invalid since it is non contained in the list of airports provided to the in dominion:

                                        

utilise Illuminate\Back up\Facades\ Validator ;

utilise Illuminate\Validation\ Rule ;

$input = [

' airports ' => [ ' NYC ' , ' LAS ' ],

];

Validator :: make ( $input , [

' airports ' => [

' required ' ,

' array ' ,

Rule :: in ([ ' NYC ' , ' LIT ' ]),

],

]);

in_array:anotherfield.*

The field nether validation must exist in anotherfield's values.

integer

The field under validation must exist an integer.

{note} This validation rule does not verify that the input is of the "integer" variable type, only that the input is of a type accustomed by PHP's FILTER_VALIDATE_INT rule. If you need to validate the input as being a number please use this rule in combination with the numeric validation rule.

ip

The field under validation must exist an IP address.

ipv4

The field under validation must be an IPv4 address.

ipv6

The field nether validation must be an IPv6 address.

json

The field under validation must be a valid JSON string.

lt:field

The field under validation must be less than the given field. The ii fields must be of the aforementioned blazon. Strings, numerics, arrays, and files are evaluated using the aforementioned conventions as the size rule.

lte:field

The field under validation must be less than or equal to the given field. The 2 fields must be of the same type. Strings, numerics, arrays, and files are evaluated using the aforementioned conventions as the size rule.

mac_address

The field nether validation must exist a MAC address.

max:value

The field under validation must exist less than or equal to a maximum value. Strings, numerics, arrays, and files are evaluated in the same fashion equally the size dominion.

mimetypes:text/plainly,...

The file nether validation must match one of the given MIME types:

                                        

' video ' => ' mimetypes:video/avi,video/mpeg,video/quicktime '

To determine the MIME type of the uploaded file, the file'southward contents volition exist read and the framework will attempt to guess the MIME type, which may be different from the client'south provided MIME type.

mimes:foo,bar,...

The file under validation must accept a MIME type corresponding to one of the listed extensions.

Basic Usage Of MIME Rule

                                        

' photo ' => ' mimes:jpg,bmp,png '

Fifty-fifty though you only need to specify the extensions, this dominion really validates the MIME blazon of the file past reading the file's contents and guessing its MIME type. A full listing of MIME types and their corresponding extensions may exist institute at the following location:

https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

min:value

The field under validation must have a minimum value. Strings, numerics, arrays, and files are evaluated in the aforementioned style as the size rule.

multiple_of:value

The field under validation must exist a multiple of value.

{note} The bcmath PHP extension is required in club to use the multiple_of rule.

not_in:foo,bar,...

The field under validation must non be included in the given listing of values. The Rule::notIn method may be used to fluently construct the rule:

                                        

use Illuminate\Validation\ Rule ;

Validator :: make ( $data , [

' toppings ' => [

' required ' ,

Dominion :: notIn ([ ' sprinkles ' , ' cherries ' ]),

],

]);

not_regex:design

The field nether validation must not match the given regular expression.

Internally, this rule uses the PHP preg_match role. The pattern specified should obey the same formatting required by preg_match and thus likewise include valid delimiters. For example: 'email' => 'not_regex:/^.+$/i'.

{note} When using the regex / not_regex patterns, it may be necessary to specify your validation rules using an array instead of using | delimiters, peculiarly if the regular expression contains a | character.

nullable

The field under validation may exist naught.

numeric

The field under validation must exist numeric.

password

The field under validation must match the authenticated user's countersign.

{annotation} This dominion was renamed to current_password with the intention of removing it in Laravel 9. Please use the Current Countersign rule instead.

present

The field under validation must exist present in the input data but tin can be empty.

prohibited

The field nether validation must be empty or non present.

prohibited_if:anotherfield,value,...

The field under validation must exist empty or non present if the anotherfield field is equal to whatever value.

If complex conditional prohibition logic is required, you may utilize the Dominion::prohibitedIf method. This method accepts a boolean or a closure. When given a closure, the closure should render true or false to indicate if the field under validation should be prohibited:

                                        

use Illuminate\Support\Facades\ Validator ;

use Illuminate\Validation\ Rule ;

Validator :: brand ( $request -> all (), [

' role_id ' => Rule :: prohibitedIf ( $request -> user () ->is_admin ),

]);

Validator :: make ( $request -> all (), [

' role_id ' => Rule :: prohibitedIf ( fn () => $asking -> user () ->is_admin ),

]);

prohibited_unless:anotherfield,value,...

The field under validation must exist empty or non present unless the anotherfield field is equal to any value.

prohibits:anotherfield,...

If the field under validation is present, no fields in anotherfield can be present, even if empty.

regex:blueprint

The field under validation must lucifer the given regular expression.

Internally, this rule uses the PHP preg_match function. The design specified should obey the same formatting required past preg_match and thus likewise include valid delimiters. For example: 'electronic mail' => 'regex:/^[email protected]+$/i'.

{note} When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using | delimiters, especially if the regular expression contains a | character.

required

The field under validation must be present in the input information and not empty. A field is considered "empty" if one of the post-obit weather are true:

  • The value is null.
  • The value is an empty string.
  • The value is an empty array or empty Countable object.
  • The value is an uploaded file with no path.

required_if:anotherfield,value,...

The field under validation must exist present and not empty if the anotherfield field is equal to any value.

If you would similar to construct a more complex status for the required_if rule, you lot may utilise the Dominion::requiredIf method. This method accepts a boolean or a closure. When passed a closure, the closure should return truthful or imitation to bespeak if the field nether validation is required:

                                        

use Illuminate\Support\Facades\ Validator ;

use Illuminate\Validation\ Rule ;

Validator :: make ( $request -> all (), [

' role_id ' => Rule :: requiredIf ( $asking -> user () ->is_admin ),

]);

Validator :: make ( $asking -> all (), [

' role_id ' => Rule :: requiredIf ( fn () => $asking -> user () ->is_admin ),

]);

required_unless:anotherfield,value,...

The field under validation must be nowadays and not empty unless the anotherfield field is equal to any value. This likewise means anotherfield must be present in the request data unless value is goose egg. If value is null (required_unless:proper noun,null), the field under validation will be required unless the comparing field is nil or the comparison field is missing from the request data.

required_with:foo,bar,...

The field under validation must be present and not empty only if any of the other specified fields are present and not empty.

required_with_all:foo,bar,...

The field nether validation must be present and non empty only if all of the other specified fields are present and not empty.

required_without:foo,bar,...

The field nether validation must be present and not empty just when any of the other specified fields are empty or not present.

required_without_all:foo,bar,...

The field under validation must be present and not empty only when all of the other specified fields are empty or not nowadays.

required_array_keys:foo,bar,...

The field under validation must exist an array and must comprise at least the specified keys.

same:field

The given field must match the field under validation.

size:value

The field under validation must have a size matching the given value. For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value (the attribute must likewise take the numeric or integer dominion). For an array, size corresponds to the count of the array. For files, size corresponds to the file size in kilobytes. Allow's look at some examples:

                                        

// Validate that a cord is exactly 12 characters long...

' title ' => ' size:12 ' ;

// Validate that a provided integer equals 10...

' seats ' => ' integer|size:10 ' ;

// Validate that an array has exactly five elements...

' tags ' => ' array|size:5 ' ;

// Validate that an uploaded file is exactly 512 kilobytes...

' image ' => ' file|size:512 ' ;

starts_with:foo,bar,...

The field under validation must start with ane of the given values.

string

The field under validation must be a string. If yous would like to allow the field to likewise be zilch, you should assign the nullable dominion to the field.

timezone

The field under validation must be a valid timezone identifier according to the timezone_identifiers_list PHP function.

unique:table,column

The field under validation must non exist within the given database table.

Specifying A Custom Table / Cavalcade Name:

Instead of specifying the table name directly, you may specify the Eloquent model which should exist used to determine the tabular array proper noun:

                                        

' email ' => ' unique:App\Models\User,email_address '

The cavalcade option may be used to specify the field's corresponding database cavalcade. If the column choice is not specified, the name of the field under validation will be used.

                                        

' electronic mail ' => ' unique:users,email_address '

Specifying A Custom Database Connection

Occasionally, you may demand to ready a custom connection for database queries fabricated past the Validator. To reach this, yous may prepend the connection proper noun to the table name:

                                        

' electronic mail ' => ' unique:connectedness.users,email_address '

Forcing A Unique Rule To Ignore A Given ID:

Sometimes, you may wish to ignore a given ID during unique validation. For instance, consider an "update profile" screen that includes the user's name, e-mail address, and location. You will probably want to verify that the email address is unique. However, if the user only changes the name field and non the email field, you lot do not want a validation error to exist thrown because the user is already the owner of the email address in question.

To instruct the validator to ignore the user'southward ID, nosotros'll use the Dominion class to fluently define the dominion. In this example, we'll also specify the validation rules as an array instead of using the | character to delimit the rules:

                                        

use Illuminate\Support\Facades\ Validator ;

employ Illuminate\Validation\ Rule ;

Validator :: make ( $data , [

' email ' => [

' required ' ,

Rule :: unique ( ' users ' ) -> ignore ( $user ->id ),

],

]);

{note} Yous should never laissez passer any user controlled request input into the ignore method. Instead, you should only pass a system generated unique ID such as an auto-incrementing ID or UUID from an Eloquent model instance. Otherwise, your application will be vulnerable to an SQL injection attack.

Instead of passing the model key's value to the ignore method, you lot may likewise pass the unabridged model instance. Laravel will automatically excerpt the key from the model:

                                        

Rule :: unique ( ' users ' ) -> ignore ( $user )

If your table uses a primary central column proper noun other than id, you may specify the name of the column when calling the ignore method:

                                        

Rule :: unique ( ' users ' ) -> ignore ( $user ->id , ' user_id ' )

By default, the unique dominion will check the uniqueness of the cavalcade matching the name of the attribute being validated. Even so, you may pass a different column name as the second statement to the unique method:

                                        

Rule :: unique ( ' users ' , ' email_address ' ) -> ignore ( $user ->id ),

Adding Additional Where Clauses:

You may specify boosted query conditions by customizing the query using the where method. For case, let's add a query condition that scopes the query to simply search records that have an account_id column value of 1:

                                        

' email ' => Dominion :: unique ( ' users ' ) -> where ( fn ( $query ) => $query -> where ( ' account_id ' , ane ))

url

The field under validation must exist a valid URL.

uuid

The field nether validation must be a valid RFC 4122 (version i, 3, 4, or five) universally unique identifier (UUID).

Conditionally Adding Rules

Skipping Validation When Fields Take Sure Values

You may occasionally wish to not validate a given field if another field has a given value. You lot may attain this using the exclude_if validation dominion. In this example, the appointment_date and doctor_name fields will non be validated if the has_appointment field has a value of false:

                                        

use Illuminate\Support\Facades\ Validator ;

$validator = Validator :: make ( $data , [

' has_appointment ' => ' required|boolean ' ,

' appointment_date ' => ' exclude_if:has_appointment,fake|required|date ' ,

' doctor_name ' => ' exclude_if:has_appointment,imitation|required|string ' ,

]);

Alternatively, you lot may employ the exclude_unless rule to non validate a given field unless another field has a given value:

                                        

$validator = Validator :: make ( $information , [

' has_appointment ' => ' required|boolean ' ,

' appointment_date ' => ' exclude_unless:has_appointment,truthful|required|appointment ' ,

' doctor_name ' => ' exclude_unless:has_appointment,true|required|string ' ,

]);

Validating When Nowadays

In some situations, you may wish to run validation checks confronting a field simply if that field is present in the data being validated. To chop-chop accomplish this, add the sometimes dominion to your rule list:

                                        

$v = Validator :: make ( $data , [

' email ' => ' sometimes|required|email ' ,

]);

In the example to a higher place, the email field will just be validated if it is present in the $data assortment.

{tip} If you lot are attempting to validate a field that should always exist present just may be empty, cheque out this note on optional fields.

Complex Conditional Validation

Sometimes you may wish to add validation rules based on more complex conditional logic. For instance, you may wish to require a given field only if another field has a greater value than 100. Or, y'all may need two fields to have a given value only when some other field is present. Adding these validation rules doesn't accept to be a hurting. First, create a Validator instance with your static rules that never change:

                                        

use Illuminate\Support\Facades\ Validator ;

$validator = Validator :: make ( $asking -> all (), [

' email ' => ' required|e-mail ' ,

' games ' => ' required|numeric ' ,

]);

Let'south presume our web awarding is for game collectors. If a game collector registers with our application and they own more 100 games, we want them to explain why they own so many games. For example, maybe they run a game resale shop, or maybe they just savor collecting games. To conditionally add together this requirement, nosotros tin can use the sometimes method on the Validator instance.

                                        

$validator -> sometimes ( ' reason ' , ' required|max:500 ' , function ( $input ) {

render $input ->games >= 100 ;

});

The first statement passed to the sometimes method is the name of the field we are conditionally validating. The second argument is a list of the rules we want to add. If the closure passed as the third argument returns true, the rules will be added. This method makes information technology a breeze to build circuitous provisional validations. You may even add conditional validations for several fields at once:

                                        

$validator -> sometimes ([ ' reason ' , ' toll ' ], ' required ' , function ( $input ) {

return $input ->games >= 100 ;

});

{tip} The $input parameter passed to your closure volition be an case of Illuminate\Support\Fluent and may be used to access your input and files under validation.

Complex Conditional Array Validation

Sometimes you may desire to validate a field based on another field in the same nested array whose index yous do not know. In these situations, you lot may allow your closure to receive a second argument which will be the current individual item in the array existence validated:

                                        

$input = [

' channels ' => [

[

' type ' => ' e-mail ' ,

' accost ' => ' [electronic mail protected] ' ,

],

[

' type ' => ' url ' ,

' address ' => ' https://example.com ' ,

],

],

];

$validator -> sometimes ( ' channels.*.address ' , ' email ' , part ( $input , $particular ) {

return $item ->type === ' electronic mail ' ;

});

$validator -> sometimes ( ' channels.*.address ' , ' url ' , role ( $input , $item ) {

return $item ->blazon !== ' email ' ;

});

Like the $input parameter passed to the closure, the $detail parameter is an instance of Illuminate\Support\Fluent when the aspect information is an assortment; otherwise, information technology is a string.

Validating Arrays

Every bit discussed in the array validation dominion documentation, the array rule accepts a list of allowed array keys. If whatsoever additional keys are present within the array, validation will fail:

                                        

use Illuminate\Support\Facades\ Validator ;

$input = [

' user ' => [

' name ' => ' Taylor Otwell ' ,

' username ' => ' taylorotwell ' ,

' admin ' => true ,

],

];

Validator :: make ( $input , [

' user ' => ' assortment:username,locale ' ,

]);

In general, y'all should always specify the assortment keys that are immune to exist present within your array. Otherwise, the validator's validate and validated methods will render all of the validated data, including the array and all of its keys, even if those keys were not validated by other nested assortment validation rules.

Validating Nested Array Input

Validating nested assortment based form input fields doesn't take to be a pain. You lot may use "dot notation" to validate attributes within an array. For case, if the incoming HTTP asking contains a photos[profile] field, you may validate it like so:

                                        

utilise Illuminate\Support\Facades\ Validator ;

$validator = Validator :: make ( $request -> all (), [

' photos.profile ' => ' required|epitome ' ,

]);

You may as well validate each element of an array. For instance, to validate that each electronic mail in a given assortment input field is unique, you may do the following:

                                        

$validator = Validator :: make ( $request -> all (), [

' person.*.email ' => ' email|unique:users ' ,

' person.*.first_name ' => ' required_with:person.*.last_name ' ,

]);

Likewise, y'all may use the * character when specifying custom validation messages in your language files, making it a cakewalk to utilize a single validation bulletin for array based fields:

                                        

' custom ' => [

' person.*.email ' => [

' unique ' => ' Each person must have a unique email address ' ,

]

],

Accessing Nested Array Information

Sometimes you may need to admission the value for a given nested assortment chemical element when assigning validation rules to the attribute. Yous may accomplish this using the Rule::forEach method. The forEach method accepts a closure that volition be invoked for each iteration of the array attribute under validation and will receive the attribute's value and explicit, fully-expanded attribute proper noun. The closure should return an array of rules to assign to the array element:

                                        

utilize App\Rules\ HasPermission ;

use Illuminate\Back up\Facades\ Validator ;

use Illuminate\Validation\ Rule ;

$validator = Validator :: brand ( $request -> all (), [

' companies.*.id ' => Rule :: forEach ( role ( $value , $aspect ) {

return [

Rule :: exists ( Visitor :: grade , ' id ' ),

new HasPermission ( ' manage-visitor ' , $value ),

];

}),

]);

Mistake Message Indexes & Positions

When validating arrays, you may want to reference the index or position of a particular item that failed validation within the error bulletin displayed by your application. To accomplish this, you may include the :index and :position place-holders inside your custom validation bulletin:

                                        

use Illuminate\Back up\Facades\ Validator ;

$input = [

' photos ' => [

[

' name ' => ' BeachVacation.jpg ' ,

' description ' => ' A photo of my beach vacation! ' ,

],

[

' proper noun ' => ' GrandCanyon.jpg ' ,

' description ' => '' ,

],

],

];

Validator :: validate ( $input , [

' photos.*.description ' => ' required ' ,

], [

' photos.*.description.required ' => ' Please draw photograph #:position. ' ,

]);

Given the case to a higher place, validation will fail and the user will be presented with the post-obit fault of "Delight describe photo #ii."

Validating Passwords

To ensure that passwords have an acceptable level of complexity, you may utilize Laravel'south Password rule object:

                                        

use Illuminate\Support\Facades\ Validator ;

use Illuminate\Validation\Rules\ Password ;

$validator = Validator :: brand ( $request -> all (), [

' password ' => [ ' required ' , ' confirmed ' , Countersign :: min ( viii )],

]);

The Password dominion object allows yous to hands customize the countersign complexity requirements for your application, such as specifying that passwords require at to the lowest degree one letter, number, symbol, or characters with mixed casing:

                                        

// Require at least eight characters...

Password :: min ( 8 )

// Require at least one letter...

Password :: min ( viii ) -> letters ()

// Require at least one majuscule and i lowercase letter...

Password :: min ( eight ) -> mixedCase ()

// Require at least one number...

Password :: min ( eight ) -> numbers ()

// Require at least i symbol...

Countersign :: min ( 8 ) -> symbols ()

In addition, yous may ensure that a password has non been compromised in a public password data alienation leak using the uncompromised method:

                                        

Password :: min ( 8 ) -> uncompromised ()

Internally, the Countersign rule object uses the k-Anonymity model to determine if a password has been leaked via the haveibeenpwned.com service without sacrificing the user's privacy or security.

By default, if a password appears at least once in a data leak, it volition be considered compromised. You lot can customize this threshold using the first statement of the uncompromised method:

                                        

// Ensure the password appears less than 3 times in the aforementioned data leak...

Password :: min ( 8 ) -> uncompromised ( 3 );

Of course, you may concatenation all the methods in the examples above:

                                        

Password :: min ( 8 )

-> messages ()

-> mixedCase ()

-> numbers ()

-> symbols ()

-> uncompromised ()

Defining Default Password Rules

You may find information technology convenient to specify the default validation rules for passwords in a single location of your application. Yous can easily accomplish this using the Password::defaults method, which accepts a closure. The closure given to the defaults method should render the default configuration of the Countersign rule. Typically, the defaults dominion should be called within the boot method of one of your application'due south service providers:

                                        

apply Illuminate\Validation\Rules\ Password ;

/**

* Bootstrap any application services.

*

* @render void

*/

public role boot ()

{

Password :: defaults ( function () {

$dominion = Password :: min ( 8 );

return $this ->app-> isProduction ()

? $rule -> mixedCase () -> uncompromised ()

: $rule ;

});

}

Then, when yous would similar to utilize the default rules to a particular password undergoing validation, yous may invoke the defaults method with no arguments:

                                        

' password ' => [ ' required ' , Countersign :: defaults ()],

Occasionally, y'all may want to adhere additional validation rules to your default password validation rules. You may use the rules method to accomplish this:

                                        

use App\Rules\ ZxcvbnRule ;

Password :: defaults ( function () {

$rule = Password :: min ( eight ) -> rules ([ new ZxcvbnRule ]);

// ...

});

Custom Validation Rules

Using Rule Objects

Laravel provides a variety of helpful validation rules; yet, you may wish to specify some of your own. One method of registering custom validation rules is using rule objects. To generate a new rule object, you lot may use the brand:dominion Artisan command. Let'southward employ this command to generate a dominion that verifies a string is capital. Laravel will place the new rule in the app/Rules directory. If this directory does not exist, Laravel volition create it when you execute the Artisan command to create your rule:

                                        

php artisan brand:rule Uppercase

Once the rule has been created, we are prepare to define its behavior. A dominion object contains 2 methods: passes and message. The passes method receives the attribute value and name, and should return true or false depending on whether the aspect value is valid or not. The message method should return the validation error message that should be used when validation fails:

                                        

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\ Dominion ;

course Uppercase implements Dominion

{

/**

* Determine if the validation rule passes.

*

* @param string $attribute

* @param mixed $value

* @return bool

*/

public function passes ( $aspect , $value )

{

return strtoupper ($ value ) === $value ;

}

/**

* Get the validation fault message.

*

* @return cord

*/

public function bulletin ()

{

return ' The :attribute must be uppercase. ' ;

}

}

You lot may call the trans helper from your bulletin method if y'all would like to return an error bulletin from your translation files:

                                        

/**

* Get the validation error message.

*

* @return string

*/

public role bulletin ()

{

return trans ( ' validation.uppercase ' );

}

One time the rule has been defined, yous may attach it to a validator by passing an instance of the rule object with your other validation rules:

                                        

use App\Rules\ Upper-case letter ;

$asking -> validate ([

' name ' => [ ' required ' , ' string ' , new Upper-case letter ],

]);

Accessing Additional Information

If your custom validation rule class needs to admission all of the other data undergoing validation, your rule grade may implement the Illuminate\Contracts\Validation\DataAwareRule interface. This interface requires your class to define a setData method. This method volition automatically be invoked by Laravel (before validation proceeds) with all of the data under validation:

                                        

<?php

namespace App\Rules;

employ Illuminate\Contracts\Validation\ Rule ;

utilize Illuminate\Contracts\Validation\ DataAwareRule ;

form Uppercase implements Dominion , DataAwareRule

{

/**

* All of the data under validation.

*

* @var array

*/

protected $information = [];

// ...

/**

* Set the data under validation.

*

* @param array $information

* @render $this

*/

public office setData ( $data )

{

$this ->data = $data ;

render $this ;

}

}

Or, if your validation dominion requires access to the validator case performing the validation, you may implement the ValidatorAwareRule interface:

                                        

<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\ Dominion ;

utilize Illuminate\Contracts\Validation\ ValidatorAwareRule ;

course Uppercase implements Dominion , ValidatorAwareRule

{

/**

* The validator instance.

*

* @var \ Illuminate \ Validation \ Validator

*/

protected $validator ;

// ...

/**

* Set the current validator.

*

* @param \ Illuminate \ Validation \ Validator $validator

* @render $this

*/

public function setValidator ( $validator )

{

$this ->validator = $validator ;

return $this ;

}

}

Using Closures

If you only need the functionality of a custom rule once throughout your awarding, you lot may employ a closure instead of a rule object. The closure receives the attribute's proper name, the attribute's value, and a $fail callback that should exist called if validation fails:

                                        

use Illuminate\Support\Facades\ Validator ;

$validator = Validator :: make ( $request -> all (), [

' title ' => [

' required ' ,

' max:255 ' ,

function ( $aspect , $value , $neglect ) {

if ( $value === ' foo ' ) {

$fail ( ' The ' . $attribute . ' is invalid. ' );

}

},

],

]);

Implicit Rules

By default, when an attribute beingness validated is non present or contains an empty string, normal validation rules, including custom rules, are not run. For example, the unique dominion will not exist run confronting an empty cord:

                                        

use Illuminate\Support\Facades\ Validator ;

$rules = [ ' proper noun ' => ' unique:users,proper name ' ];

$input = [ ' proper name ' => '' ];

Validator :: make ( $input , $rules ) -> passes (); // true

For a custom rule to run even when an attribute is empty, the rule must imply that the attribute is required. To create an "implicit" rule, implement the Illuminate\Contracts\Validation\ImplicitRule interface. This interface serves as a "marker interface" for the validator; therefore, it does non comprise whatsoever boosted methods y'all need to implement beyond the methods required past the typical Dominion interface.

To generate a new implicit rule object, you may use the make:rule Artisan command with the --implicit option :

                                        

php artisan brand:rule Uppercase --implicit

{annotation} An "implicit" rule only implies that the aspect is required. Whether it actually invalidates a missing or empty attribute is up to you.

stapletonforritan48.blogspot.com

Source: https://laravel.com/docs/9.x/validation

0 Response to "Laravel Check if Uploaded File Is Actula Type"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel