简体   繁体   中英

custom validation in laravel

I am integrating Amazon MWS in Laravel, so far so good, Now, in my dashboard, I have created a form where user can put his Seller ID and Auth Token ( provided by Amazon). My code looks like this

$store = StoreController::Find($id)->first();

$this->validate($request, [
'name'          => 'required|max:255',
'merchantId'    => 'required|max:255',
'authToken'     => 'required|max:255',
'marketplaceId' => 'required|max:255',
]);
 $mws    = new mwsController();
$result = $mws->checkCredentials($store);

if ($result) {
//credentials OK, Force Fill in database
//OK with it
// ALSO, I want to disable future Form Edits, any idea?
}else{
//return error on form, saying Merchant ID and Auth Token pair is invalid
//stuck at this point
//documentation doesnt help
}

1: Problem 1: How can I return custom error as I commented in Code

2: I want to disable future edits in Form If Credentials Ok

Explanation

Once I have validated credentials, and updated it Database, I want that user can see the form, but he can not edit Auth Token , Merchant ID or any other field in the form.

Any guide line and help is highly appreciated thanks

I would keep your validation in the validate method. That way your error response will work out of the box. How to extend the validator is explained here: https://laravel.com/docs/5.0/validation#custom-validation-rules

It could look something like this:

Validator::extend('mwsToken', function($attribute, $value, $parameters)
{
    // check if the token is valid an return result
});

And then you can just use it in your controller:

$this->validate($request, [
'name'          => 'required|max:255',
'merchantId'    => 'required|max:255',
'authToken'     => 'required|max:255|mwsToken',
'marketplaceId' => 'required|max:255',
]);

No need for the if/else anymore. You can just assume the token is valid there, since validation already passed. And error reporting will work automatically if you set up your Validator correctly.


As for the second question, not really sure what you mean. If you do not want to allow edits in certain cases, just don't render the form. Something like this perhaps (in your controller):

public function getEdit($id) {
   $model = Model::findOrFail($id);

   if ($model ->hasPropertyThatMeansNoEdit()) {
      abort(403);
   }

   // build and render edit form
}

Don't forget to do something similar in your post handler. Always assume the user is malicious. It isn't because there is no form, that a POST request can't be made, ie. by manipulating the request of a different model.


One last side note on your architecture. I noticed in your snippet you are calling your controllers directly ( StoreController , mwsController ). I don't think you should be doing that. Controllers are there to handle your requests, and nothing else. If you have reusable blocks of code in them, consider moving that code to a Service or a Command, and calling that command from inside your controller. It will make your controllers a lot cleaner (SRP) and makes it easier to reuse those Commands later in ie. an API or a Queue Job or something like that.

The answer to your first question is pointed out in the docs : simply add a message bag to the response. Also check out the beginner tutorial video's (by Jeffrey Wade) on Laracast, they are really helpful. The code would be:

public function store(Request $request, $id)
{
    // ...

    $this->validate($request, [
        'name'          => 'required|string|max:255',
        'merchantId'    => 'required|integer|max:255',
        'authToken'     => 'required|string|max:255',
        'marketplaceId' => 'required|integer|max:255',
    ]);

    $mws = new mwsController();
    if ($mws->checkCredentials($store)) {
        // Your code here
        return redirect('home')->with(['success' => 'Everything OK']); // Flash session
    }

    return redirect('home')->withErrors(['Merchant ID and Auth Token pair is invalid']); // Error bag
}

And to display:

@if (session('success'))
    <div class="positive message">{{ session('success') }}</div>
@endif

@if (count($errors) > 0)
    <div class="negative message">{{ $errors->first() }}</div>
@endif

You're second question is pretty hard to answer since you've given no code or example to work with. Maybe I'm not understanding the question, but I think you are looking for middleware .

Edit: To answer the second question, add a column named 'validated' (default 0 ) in your database table. If the credentials are OK, update that column and set it to 1 . Use that variable in your template to manipulate the form fields, for instance:

<input type="text" name="merchantId" {{ $validated ? '' : 'disabled' }}/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM