PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label laravel-validation. Show all posts
Showing posts with label laravel-validation. Show all posts

Wednesday, November 16, 2022

[FIXED] How to use logical operator in a laravel validation?

 November 16, 2022     laravel, laravel-6, laravel-validation     No comments   

Issue

I created a working validator for checking the phone to my AppServiceProvider.php

Validator::extend('phone', function ($attribute, $value, $parameters, $validator) {
    return preg_match('/^09[0-9]{9}$/', $value);
});

Now this time I want to validate for my username that accepts either email or phone. Something like below.

'username' => 'email OR phone'

As expected that code above will not work. Somebody knows how to achieve? I really needing this for my project.


Solution

How about you create another validator for username so you can perform logical operator.

Validator::extend('username', function ($attribute, $value, $parameters, $validator) {
    $emailPattern = '/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}@)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*@(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-+[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-+[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD';

    return preg_match('/^09[0-9]{9}$/', $value) || preg_match($emailPattern, $value);
});

Now you can use it.

'username' => 'username'


Answered By - tempra
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 11, 2022

[FIXED] How do you display your own error messages with laravel-jsvalidation?

 July 11, 2022     jsvalidation, laravel, laravel-validation, message, php     No comments   

Issue

I would like to figure out how to create your own error messages for your rules (e.g. regular expression rules) to be reused by both server PHP and client javascript (using jqueryvalidation through laravel-jsvalidation )

I have tried and can not make it work, and below is a small example to show what I am trying to do but it does not work.

What am I doing wrong?

My small example:

In the file "routes\web.php":

    Route::get('/minimal_example_laravel_jsvalidation', function() {
        // Of course these rules should not really be defined here since 
        // the purpose of the rules is to also reuse them from PHP Laravel code
        // but my problem is now how to generate javascript that can 
        // reuse the same rules and therefore I just put the rules and messages
        // here in this minimalistic example illustrating the problem
        $rules = [
            'three_digits' => 'required|regex:/^\d{3}$/'
        ];    
        $messages = [
            'three_digits' => 'Must be exactly three digits'
        ];
        $validator = JsValidator::make($rules, $messages);
        return view('minimal_example_laravel_jsvalidation')->with("validator", $validator);
    });    

In the file "resources\views\minimal_example_laravel_jsvalidation.blade.php":

...
{!! $validator->selector('#myForm') !!}
...

When using the URL http://localhost:8000/minimal_example_laravel_jsvalidation with the web browser and then "view source" I can see that the following javascript code has been generated by the above "$validator->selector" :

    jQuery(document).ready(function(){

        $("#myForm").each(function() {
            $(this).validate({
                errorElement: 'span',
                errorClass: 'invalid-feedback',

                errorPlacement: function (error, element) {
                    if (element.parent('.input-group').length ||
                        element.prop('type') === 'checkbox' || element.prop('type') === 'radio') {
                        error.insertAfter(element.parent());
                        // else just place the validation message immediately after the input
                    } else {
                        error.insertAfter(element);
                    }
                },
                highlight: function (element) {
                    $(element).closest('.form-control').removeClass('is-valid').addClass('is-invalid'); // add the Bootstrap error class to the control group
                },



                unhighlight: function(element) {
                    $(element).closest('.form-control').removeClass('is-invalid').addClass('is-valid');
                },

                success: function (element) {
                    $(element).closest('.form-control').removeClass('is-invalid').addClass('is-valid'); // remove the Boostrap error class from the control group
                },

                focusInvalid: true,

                rules: {"three_digits":{"laravelValidation":[["Required",[],"The three digits field is required.",true],["Regex",["\/^\\d{3}$\/"],"The three digits format is invalid.",false]]}}            });
        });
    });

Indeed, the error message I get when not writing three digits in the field through my web browser, is as above "The three digits format is invalid." while I expect that it instead should be "Must be exactly three digits" as I defined in the "$messages" array.

I have seen that it is possible with Laravel to create PHP classes with "Custom Validation Rules" where you also can define custom messages, but as far as I understand, if you use those custom rules with laravel-jsvalidation then the validation must be done with AJAX instead of javascript validation directly within the browser, which is what I want to do instead of doing AJAX calls.

I am using these versions:

laravel/framework v7.4.0

proengsoft/laravel-jsvalidation 3.0.0


Solution

Try changing messages array like this,

$messages = [
     'three_digits.required' => 'Three Digits field is required',
     'three_digits.regex' => 'Must be exactly three digits'
];

Note I have added rule also to the message key. ('three_digits.required')



Answered By - vimuth
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, April 19, 2022

[FIXED] How to add two unique validation for one input

 April 19, 2022     laravel, laravel-5.8, laravel-validation, php, validation     No comments   

Issue

I'm trying to validate an input like this:

$validatedPhone = $request->validate([
        'user_input' => 'required|unique:users,user_name|regex:/^09\d{9}$/|max:11|min:11',
]

Now I need to say that the value of this input does not exist at another table which is members table and member_mobile column.

But I have already defined a unique rule for the users table with user_name column.

So how to define two unique rules for two different tables for validating one input?


Solution

Just add another rule as shown below

 $validatedPhone = $request->validate([
        'user_input' => 'required|unique:users,user_name|unique:members,member_mobile|regex:/^09\d{9}$/|max:11|min:11',
    ]


Answered By - Donnicias
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 2, 2022

[FIXED] How to use the request route parameter in Laravel 5 form request?

 March 02, 2022     laravel, laravel-5, laravel-routing, laravel-validation, php     No comments   

Issue

I am new to Laravel 5 and I am trying to use the new Form Request to validate all forms in my application.

Now I am stuck at a point where I need to DELETE a resource and I created a DeleteResourceRequest for just to use the authorize method.

The problem is that I need to find what id is being requested in the route parameter but I cannot see how to get that in to the authorize method.

I can use the id in the controller method like so:

public function destroy($id, DeletePivotRequest $request)
{
    Resource::findOrFail($id);
}

But how to get this to work in the authorize method of the Form Request?


Solution

That's very simple, just use the route() method. Assuming your route parameter is called id:

public function authorize(){
    $id = $this->route('id');
}


Answered By - lukasgeiter
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 28, 2022

[FIXED] Laravel update request validation not working on 9.x

 February 28, 2022     laravel, laravel-validation, request-validation, validation     No comments   

Issue

I have create a validation request file on request folder. It working fine in new insert. But when i update, it's not working also i pass the unique $id but not working.

a. Resource controller update method

public function update(KlassNameRequest $request, $id)
{
    $validated = $request->validated();
    KlassName::where('id', $id)->update($validated);
}

b. Validation code

public function rules()
{
    return [
        'name'          => 'required|unique:klass_names|max:128,' . $this->id,
        'ref'           => 'required|unique:klass_names|numeric|between:1,999,' . $this->id,
        'seat_quota'    => 'required|numeric|between:1,9999',
        'division'      => 'required',
        'semester'      => 'required',
    ];
}

This message shows me when i update

This message shows me when i update


Solution

I have solve my problem in this way -

a. Add extra input hidden field passing id for $request method. Because my route is resource group route -

<form action="{{ route('adm.kls.update', $kls->id) }}" method="post">
    @csrf
    @method('PUT')

    <input type="hidden" name="id" value="{{ $kls->id }}">
</form>

b. Some editing in validation code.

public function rules() {
  return [
    'name' => 'required|max:128|unique:klass_names,name,' . $this->id,
    'ref' => 'required|numeric|between:1,999|unique:klass_names,ref,' . $this->id,
    'seat_quota' => 'required|numeric|between:1,9999',
  ];
}

done.



Answered By - mahbubrn
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Laravel 5.7 - Override all() method in Request validation Class to validate route parameters?

 February 28, 2022     laravel, laravel-5, laravel-5.7, laravel-request, laravel-validation     No comments   

Issue

I want to validate the route parameters in the Request validation class. I know this question has been asked many times before but According to this question I override all() method and I receive this error:

Class App\Http\Requests\DestroyUserRequest does not exist

I'm using Laravel 5.7.

Route:

Route::delete('/user/{userId}/delete', 'UserController@destroy')->name('user.destroy');

Controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\DestroyUserRequest;
use App\User;

class UserController extends Controller
{

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy(DestroyUserRequest $request)
    {
        User::find($request->route('userId'))->delete();
        return $request->route('userId');
    }
}

DestroyUserRequest:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class DestroyUserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'userId' => 'integer|exists:users,id'
        ];
    }

    public function all()
    {
        $data = parent::all();
        $data['userId'] =  $this->route('userId');
        return $data;
    }
}

What is wrong to override all() method?


Solution

The error your get seems to be quite strange. I believe the problem is here because your method signature is not the same as parent.

It should be:

public function all($keys = null)
{
    $data = parent::all($keys);
    $data['userId'] =  $this->route('userId');
    return $data;
}

because signature of Illuminate/Http/Concerns/InteractsWithInput.php is:

/**
 * Get all of the input and files for the request.
 *
 * @param  array|mixed  $keys
 * @return array
 */
public function all($keys = null)

The change was made in Laravel 5.5. You can read in upgrade guide:

The all Method

If you are overriding the all method of the Illuminate\Http\Request class, you should update your method signature to reflect the new $keys argument:

public function all($keys = null) {



Answered By - Marcin Nabiałek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, February 25, 2022

[FIXED] Laravel Validation for integers or specific word

 February 25, 2022     laravel, laravel-5, laravel-validation, php, regex     No comments   

Issue

I'm creating a validation rule where location attribute can have any integer or a word "all" value.
For integer validation I use this rule:

'location' => 'required|integer'
and for a particular word I can use this rule:

'location' => ['required', Rule::in([all])] 

How can apply both of rules together so that location can either be any integer or the word "all"? Can regex be of any help here?


Solution

$this->validate($request, [
    'location' => [
        'required',
        'max:255',
        function ($attribute, $value, $fail) {
            if( is_int( $value ) || 'all' === $value ) {
                return true;
            } else {
                $fail($attribute.' is invalid.');
            }
        },
    ],
]);

But keep in mind: If you send integer via form – you will receive string. And checking is_int( $value ) will not be passed.



Answered By - Serhii Topolnytskyi
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 20, 2022

[FIXED] Laravel Validation Error Message required_if not working

 February 20, 2022     laravel, laravel-5.2, laravel-validation, php     No comments   

Issue

I am validating a form using Laravel 5.2

using validation check required_if for input youtube-embed. validation takes place successfully but the custom error message does not work. Here is the code maybe some one can take a look.

$messages = [
        'youtube-embed.required_if' => 'Please paste in your youtube embed code',
    ];

$this->validate($request, [
        'youtube-embed'      => 'required_if:youtube,on',
    ]);

This is the error message that laravel is returning instead of my custom error:

The youtube-embed field is required when youtube is on.

Solution

Try this:

$this->validate($request, 
    ['youtube-embed'      => 'required_if:youtube,on',], 
    ['required_if' => 'Please paste in your youtube embed code',]
);

Basically you can pass your custom messages as third parameter in validate function.



Answered By - Can Celik
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, February 19, 2022

[FIXED] validating a numeric input's length in laravel 5

 February 19, 2022     laravel, laravel-5, laravel-5.2, laravel-validation, php     No comments   

Issue

foo.blade.php

<input type="text" name="national-id" />

FooController.php

$rules = [
    'national-id' => 'required|size:10|numeric'
];

the national-id field should contain 10 digits and I actually expected the code above to validate this , but instead It will check If the national-id exactly equals to 10 or not ...

how can I validate the length of a numeric field?


Solution

In fact you don't need to use digits_between rule. You can use digits rule so according to documentation it will be enough to use:

$rules = [
    'national-id' => 'required|digits:10'
];

without numeric rule because digits rule also verify if given value is numeric.



Answered By - Marcin Nabiałek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, February 17, 2022

[FIXED] Laravel 5.7 validation makes nothing

 February 17, 2022     laravel, laravel-5, laravel-validation, validation     No comments   

Issue

My function works by itself but the validation is not executed. Does anyone know what I forgot to add?

This is a snippet of my code:

namespace App\Http\Controllers;

use App\Player;
use App\Tournament;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;


    public function store(Request $request)
    {
       $data=$request->all();
$validator = Validator::make($data, [
            'first_name' => 'alpha|min:2|max:30',
        ]);
        
        
        
        if(Auth::check()){

            $foo = Foo::create([
                'first_name' => $request->input('fist_name'),
                'last_name' => $request->input('last_name'),
            ]);
 
            if($foo){
                return redirect()->route('foo.show', ['foo'=> $foo->id])
                ->with('success' , 'Foo created!');
            }
 
        }
         
        return back()->withInput()->with('errors', 'Error when creating the foo');
    }

enter image description here

Thanks in advance


Solution

try different approach like:

use Illuminate\Support\Facades\Validator;

...
$data=$request->all();
$validator = Validator::make($data, [
            'first_name' => 'alpha|min:2|max:30',,  
        ]);


Answered By - JahStation
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, February 10, 2022

[FIXED] Validate datetime-local input

 February 10, 2022     laravel, laravel-5, laravel-5.4, laravel-validation     No comments   

Issue

According to MDN, I should use datetime-local type for a date and a time input:

<input type="datetime-local">

I can validate a date in laravel with this code (in a controller):

$this->validate($request, ['my_date' => 'required|date']);

But is there a way to validate a datetime-local?


Solution

You can use date_format:format or date to validate. All date validation is performed by php strtotime

The best way to know for sure is to test this. Create your rules function in the controller and test, that way you know for sure for your laravel version and your php version as you don't mention that information.



Answered By - Glenn Plas
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 6, 2022

[FIXED] Laravel validation rule to enforce unique combinations?

 February 06, 2022     laravel, laravel-validation, php     No comments   

Issue

I have two columns A & B in the same table. Column B can accept only unique values for each value of Column A.

column A column B
1 8
1 52
1 8 not allowed because value 8 in Column B has already been set for value 1 in column A
2 78
2 2
2 78 not allowed because value 78 in Column B has already been set for value 2 in column A

etc ...

I'm trying to write a validation rule that can do this verification but I'm having trouble.


Solution

If you want to do this in a validator, use a custom validation rule:

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

$validator = Validator::make($request->all(), [
    // Change column_b here to the name of your input
    'column_b' => function ($attribute, $value, $fail) use ($request) {
        $columnB = $value;
        // Change column_a here to the name of your input
        $columnA = $request->input('column_a');

        $records = DB::table('YOUR_TABLE')
            ->select('*')
            // Change column_a here to the name of column A in your database
            ->where('column_a', $columnA)
            // Change column_b here to the name of column B in your database
            ->where('column_b', $columnB)
            ->count();

        if($records > 0) {
            $fail("not allowed because value $columnB in Column B has already been set for value $columnA in column A");
        }
    },
]);


Answered By - Joundill
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 28, 2022

[FIXED] Integer or String for a phone number?

 January 28, 2022     laravel, laravel-5, laravel-validation, validation     No comments   

Issue

I want to know if I have to use a string or an integer for a phone number?

I have tried an integer but I have a problem in my validation.

... table->integer('phone'); ...

In my validation, I must have between 8 and 11 characters.

I have tried this, but it doesn't work:

'phone' => 'required|numeric|between:8,11',

I think the string is better?


Solution

I think the validation should be like this

'phone' => 'required|numeric|min:8|max:11',


Answered By - ashok poudel
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, January 26, 2022

[FIXED] Laravel 5 how to validate route parameters?

 January 26, 2022     laravel, laravel-5, laravel-request, laravel-validation, routes     No comments   

Issue

I want to validate the route parameters in the "form request" but don't know how to do it.

Below is the code sample, I am trying with:

Route

// controller Server
Route::group(['prefix' => 'server'], function(){
    Route::get('checkToken/{token}',['as'=>'checkKey','uses'=> 'ServerController@checkToken']);
});

Controller

namespace App\Http\Controllers;


use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Http\Requests;


class ServerController extends Controller {
    public function checkToken( \App\Http\Requests\CheckTokenServerRequest $request) // OT: - why I have to set full path to work??
        {   
            $token = Token::where('token', '=', $request->token)->first();      
            $dt = new DateTime; 
            $token->executed_at = $dt->format('m-d-y H:i:s');
            $token->save();

            return response()->json(json_decode($token->json),200);
        }
}

CheckTokenServerRequest

namespace App\Http\Requests;

use App\Http\Requests\Request;

class CheckTokenServerRequest extends Request {

        //autorization

        /**
         * Get the validation rules that apply to the request.
         *
         * @return array
         */
        public function rules()
        {

            return [
                'token' => ['required','exists:Tokens,token,executed_at,null']
            ];
        }

}

But when I try to validate a simple url http://myurl/server/checkToken/222, I am getting the response: no " token " parameter set.

Is it possible to validate the parameters in a separate "Form request", Or I have to do all in a controller?

ps. Sorry for my bad English.


Solution

For Laravel < 5.5:
The way for this is overriding all() method for CheckTokenServerRequest like so:

public function all() 
{
   $data = parent::all();
   $data['token'] = $this->route('token');
   return $data;
}

EDIT
For Laravel >= 5.5:
Above solution works in Laravel < 5.5. If you want to use it in Laravel 5.5 or above, you should use:

public function all($keys = null) 
{
   $data = parent::all($keys);
   $data['token'] = $this->route('token');
   return $data;
}

instead.



Answered By - Marcin Nabiałek
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, January 17, 2022

[FIXED] How to validate multiple fields selectively using a common class in PHP laravel while returning all errors

 January 17, 2022     laravel, laravel-validation, php     No comments   

Issue

Just started with my first PHP laravel project, and I have this

UserRepository.php

public function validateNewEmail(Request $request, $emailName) {
    $request->validate([
        $emailName => ['required', 'email', 'unique:users'],
    ]);
}

public function validateNewPassword(Request $request, $passwordName) {
    $request->validate(
        // rule
        [
            $passwordName => ['required', 'min:8', 
                    'regex: // some long long regex'
        ],
        // message
        [
            $passwordName.".regex" => "Your new password must be more than 8 characters long, should contain at-least 1 uppercase, 1 lowercase, 1 numeric and 1 special character.",
        ]
    );
}

// Usr Id is by itself as it might be optional in registering.
public function validateNewUsrId(Request $request, $userIdName) {
    $request->validate([
        $userIdName => 'required|unique:users',
    ]);
}

And I can then use this repository easily like this in my controller.

$this->userRepository->validateNewEmail($request, "email");
$this->userRepository->validateNewPassword($request, "password");
$this->userRepository->validateNewUsrId($request, "usr_id");

The reason is because there might be multiple controllers that use the same rules, thus putting them in one place is better

However, I realised that this method does not work because it returns the first error only. For example when both the email and password is wrong, only the email error gets returned to the frontend.

What is the best way to achieve what I want? I want to put all my validation/rules in one place to be reused.

My first solution is this: Each function returns the error MessageBag which is then joined together. I will use return $validator->errors(); to return the MessageBag which can be found here https://laravel.com/docs/8.x/validation#retrieving-the-first-error-message-for-a-field

However I slightly dislike it because then in order to check for whether an error occured, I would need to check if MessageBag is empty and then throw an error which seems a little weird.

The other way I thought of is to return the rules instead, so that I can join them in my controller and then validate all in one go. This seems better but I have to combine the error messages as well, which can be a little tricky if there are multiple (since the key is not fixed, see the code $passwordName.".regex" for example.), as I will need to update the key to each message.

The best way for me, is if I could return a validator for each function, and then use some sort of Validate::ValidateAll function? Is that possible?

How is this implemented usually?


Solution

Modern Laravel applications typically use form request validation. With this approach, Laravel handles all the validation and returns error messages automatically. Simply write your form request class, and then use it in place of Request in your controller methods:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rules\Password;

class MyFormRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        return [
            'email' => ['required', 'email', 'unique:users'],
            'password' => [
                'required',
                Password::min(8)->mixedCase()->numbers()->symbols()
            ],
            'usrid' => ['required', 'unique:users'],
        ];
    }
}
public method store(MyFormRequest $request)
{
    // $request has been validated, no further checking needed
}

Note I'm using Laravel's built-in password validation rules instead of relying on a "long long regex."



Answered By - miken32
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing