0% found this document useful (0 votes)
7 views

Laravel Part-10

Uploaded by

waver58650
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Laravel Part-10

Uploaded by

waver58650
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Video-31 (form validation validate method in Laravel):-

--------------------------------------------------------------------------
Validating Form
a. Validate() Method
b. Form Request Validation

Validate ( ) Method
a. validate ( ) Method is used to validate the application's incoming
data.
b. Validate method is available on all incoming HTTP Requests.

c. Validate method provided by the Illuminate\Http\Request object.

d. If the validation rules pass, your code will keep executing


normally; however, if validation fails, an exception will be thrown
and the proper error response will automatically be sent back to
the user.
e. If validation fails during a traditional HTTP request, a redirect
response to the previous URL will be generated.

f. If the incoming request is an XHR request, a JSON response


containing the validation error messages will be returned.

Example:-
App\Http\Controllers\RegistrationController.php
public function signup(Request $request)
{
// single Rule
$validate=$request->validate([
'name'=>'required',
'email'=>'required',
'pass'=>'required'
]) ;
// The form is valide
}

Validation Rules
a. Rules specified as Array
public function signup(Request $request)
{
// Rules specified as array
$validate=$request->validate([
'name'=>['required'],
'email'=>['required','min:20'],
'pass'=>['required'],
]) ;
}

b. Rules specified using a single | delimited String


public function signup(Request $request)
{
// Rules specified using a single | delimited string
$validate=$request->validate([
'name'=>'required',
'email'=>'required'|'min:20',
'pass'=>'required',
]) ;
}

1. accepted - The field under validation must be "yes", "on", 1, or


true. This is useful for
2. validating "Terms of Service" acceptance or similar fields.
3. alpha - The field under validation must be entirely alphabetic
characters.
4. alpha_dash - The field under validation may have alpha-numeric
characters, as well as dashes and underscores.
5. alpha_num - The field under validation must be entirely
alpha-numeric characters.
6. array - The field under validation must be a PHP array.

7. boolean - The field under validation must be able to be cast as a


boolean. Accepted input are true, false, 1, 0, "1", and "0".

8. confirmed - The field under validation must have a matching field


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

9. date - The field under validation must be a valid, non-relative date


according to the strtotime PHP function.
10. digits:value - The field under validation must be numeric and
must have an exact length of value.

11. email - The field under validation must be formatted as


an email address.
12. file - The field under validation must be a successfully
uploaded file.
13. filled - The field under validation must not be empty when it
is present.
14. image - The file under validation must be an image (jpg,
jpeg, png, bmp, gif, svg, or webp).
15. integer - The field under validation must be an integer.

16. max:value - The field under validation must be less than


or equal to a maximum value.Strings, numerics, arrays,
and files are evaluated in the same fashion as the size rule.
17. min:value - The field under validation must have a minim
-um value. Strings, numerics, arrays, and files are
evaluated in the same fashion as the size rule.
18. nullable - The field under validation may be null.
19. numeric - The field under validation must be numeric.
20. password - The field under validation must match the
authenticated user's password.
21. required - The field under validation must be present in
the input data and not empty. A field is considered "empty"
if one of the following conditions 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.

22. 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 also have the numeric or integer rule). For
an array, size corresponds to the count of the array. For
files, size corresponds to the file size in kilobytes.
23. string - The field under validation must be a string. If you
would like to allow the field to also be null, you should
assign the nullable rule to the field.
24. unique:table,column,except,idColumn - The field
under validation must not exist within the given database table.

25. url - The field under validation must be a valid URL.

Display validation error practical


1. An $errors variable is shared with all of your application's views
by the Illuminate\View\Middleware\ShareErrorsFromSession
middleware, which is provided by the web middleware group.

2. When this middleware is applied an $errors variable will always


be available in your views, allowing you to conveniently assume
the $errors variable is always defined and can be safely used.

3. The $errors variable will be an instance of Illuminate\


Support\MessageBag.

Video-32(Displaying validation error custom error message in


Laravel):-
----------------------------------------------------------------------------------
Displaying Validation Errors
1. Retrieving All Error Messages For All Fields
To retrieve an array of all messages for all fields, use the all method.
@if ($errors->any())
@foreach ($errors->all() as $message)
{{$message}}
@endforeach
@endif

@if ($errors->any())
<ul>
@foreach ($errors->all() as $message)
<li> {{$message}}</li>
@endforeach
</ul>
@endif
2. Retrieving All Error Messages For A Field
If you need to retrieve an array of all the messages for a given
field, use the get method:
@if ($errors->any())
<ul>
@foreach ($errors->get('email') as $message)
<li>{{$message}}</li>
@endforeach
</ul>
@endif

If you are validating an array form field, you may retrieve all of the
messages for each of the array elements using the * character:
@foreach ($errors->get(‘attachments.*’) as $message)
{{$message}}
@endforeach

3. Retrieving The First Error Message For A Field


To retrieve the first error message for a given field, use the
first method:
$errors = $validator->errors();
echo $errors->first('email’);
@if ($errors->any())
{{$errors->first('email')}}
@endif

4. Determining If Messages Exist For A Field


The has method may be used to determine if any error messages
exist for a given field.
if ($errors->has('email')) {
//
}
@if ($errors->any())
@if ($errors->has('email'))
<h3>Error maujood hai is field me</h3>
@endif
@endif

5. Error Directive (Best tarika)


You may use the @error Blade directive to quickly determine if
validation error messages exist for a given attribute. Within an
@error directive, you may echo the $message variable to display
the error message.
Email: <input type="email" name="email" id="email"
value="{{old('email')}}"> <br>
@error('email')
<span style="color: red">{{$message}} <br></span>
@enderror

6. Specifying Custom Messages In Language Files


1. Modifying Default Error Messages
a. Laravel's built-in validation rules each have an error message that
is located in your application's resources/lang/en/validation.php
file.
b. Within this file, you will find a translation entry for each validation
rule.
c. You are free to change or modify these messages based on the
needs of your application.

2. Custom Messages For Specific Attributes


a. You may customise the error messages used for specified
attribute and rule combinations within your application's validation
language files.
b. To do so, add your message customizations to the custom array
of your application's resources/lang/en/validation.php
language file:
'custom' => [
'email' => [
'required' => 'Email dena jaroori hai',
],
],

3. Replacing default :attribute Placeholder


a. Many of Laravel's built-in error messages include an :attribute:
placeholder that is replaced with the name of the field or attribute
under validation.
b. If you would like the :attribute portion of your validation message
to be replaced with a custom value, you may specify the custom
attribute name in the attributes array of your
resources/lang/en/validation.php language file:
'attributes' => [
'email'=>'email address',
'pass'=>'pwd field',
],

Video-33(Custom Validation rule in Laravel):-


------------------------------------------------------------
There are two ways to custom validation : -
a. Using Rule objection
b. Using Closures

1. Using Rule Objection


To generate a new rule object, you may use the make:rule Artisan
command.

Laravel will place the new rule in the app/Rules directory. If this
directory does not exist, Laravel will create it when you execute the
Artisan command to create your rule.
php artisan make:rule RuleName

Using Rule Objects


<?php

namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;

class Uppercase implements Rule


{
public function passes($attribute, $value)
{
return strtoupper($value)===$value;
}

public function message()


{
return 'The :attribute must be Uppercase.';
}
}
a. The passes method receives the attribute value and name and should
return true or false depending on whether the attribute value is valid or not.

b. The message method should return the validation error message that
should be used when validation fails.
c. import in controller : -use App\Rules\Uppercase;

$request->validate([
'name'=>['required',new Uppercase],
]);

2. Using Closures
a. If you only need the functionality of a custom rule once throughout
your application, you may use a closure instead of a rule object. The
closure receives the attribute's name, the attribute's value, and a
$fail callback that should be called if validation fails.

b. use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
‘name' => [
'required',
‘max:20',
function ($attribute, $value, $fail) {
if ($value === ‘sonam') {
$fail('The '.$attribute.' is invalid.');
}
}, ],]);
$validate=$request->validate([
'name'=>['required',
function ($attribute,$value,$fail){
if($value==='admin')
{
$fail('The' .$attribute. 'is invalid');
}
}
],
dd($validate);//Here all details inside the validation method.

Video-34(Form request validation in Laravel):-


--------------------------------------------------------------
1. For more complex validation scenarios, you may wish to create a
"form request".
2. Form requests are custom request classes that encapsulate their own
validation and authorization logic.
3. To create a form request class, you may use the make:request Artisan
CLI command:
php artisan make:request RegistrationRequest
4. The generated form request class will be placed in the
app/Http/Requests directory.
5. The authorize() method is responsible for determining if the currently
authenticated user can perform the action represented by the request.

6. The rules() method returns the validation rules that should apply to the
request's data.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegisterationRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name'=>'required',
'email'=>'required',
'pass'=>'required'
];
}
}

Location of controller: - App\Http\Controllers\RegisterationController


public function signup(RegisterationRequest $request)
{
$request->validate();
$input=$request->except('_token');
// dd($input);
return view('welcome',['data'=>$input]);
}

Customizing The Error Messages


You may customize the error messages used by the form request by
overriding the messages method. This method should return an array of
attribute / rule pairs and their corresponding error messages.
public function messages()
{
return [
‘name.required' => ‘Naam Jaruri hai',
];
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class RegisterationRequest extends FormRequest


{
public function authorize()
{
return true;
}

public function rules()


{
return [
'name'=>'required',
'email'=>'required',
'pass'=>'required'
];
}
public function messages()
{
return[
'name.required'=>'Name jaroori hai',
];
}
}

Customizing The Validation Attributes


Many of Laravel's built-in validation rule error messages contain an :attribute
placeholder. If you would like the :attribute placeholder of your validation
message to be replaced with a custom attribute name, you may specify the
custom names by overriding the attributes method. This method should
return an array of attribute / name pairs.
public function attributes()
{
return [
'email' => 'email address',
];
}
<?php

namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;

class RegisterationRequest extends FormRequest


{
public function authorize()
{
return true;
}

public function rules()


{
return [
'name'=>'required',
'email'=>'required',
'pass'=>'required'
];
}
public function messages()
{
return[
'name.required'=>'Name jaroori hai',
];
}
public function attributes()
{
return [
'email'=>'email-address',
];
}
}

You might also like