0

In Laravel 5, using a form request to act as a validation gate, and given the code below:

Controller

public function decline(Request $request, InviteDeclineRequest $validation, $id)
{
    $invite = Invite::find($id);
    $invite->status = 'declined';
    $invite->save();   
}

FormRequest

class InviteDeclineRequest extends Request {

    public function rules()
    {
        return [
            # this is referring to the incoming data, 
            # not the existing data 
            'status': 'pending', 
        ];
    }

}

How can I change the above validation ruleset to say, the incoming input is only valid if the existing record's status is set to 'pending'. I.e don't allow a declined invite unless the existing is pending.

Option 1: Put this logic in the controller. Maybe the above isn't considered a part of validation, (although I would argue that it is), and so doesn't belong in the FormRequest.

Option 2: Put the logic in the Authorise method of method of the FormRequest. The only downside to this is that the authorise should be for access control, not data validation.

Option 3: Extend form request to include a third method that validates existing data as well as incoming data. Slightly painful as I need to make sure it gets called as part of the request cycle.

Option 4: Add a custom validation rule: http://laravel.com/docs/5.0/validation#custom-validation-rules

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Chris
  • 54,599
  • 30
  • 149
  • 186

1 Answers1

1

You can add to your custom InviteDeclineRequest class method all to add id to data that will be validated:

public function all()
{
        $data = parent::all();
        $segments = $this->segments();
        $id = intval(end($segments));
        if ($id != 0) {
           $data['id'] = $id;
        } 
        return $data;
}

and now in rules you can use it:

public function rules()
{
    return [
        'id' => ['required', 'exists:invites,id,status,pending']
    ];
}

to make sure record you edit has status pending.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
  • You can access the route parameter like `$this->id` and validate them with `'id' => 'required|exists:invites,id,status,pending' . $this->id`. [More about this here](https://laracasts.com/discuss/channels/requests/laravel-5-validation-request-how-to-handle-validation-on-update). – Mahozi Apr 18 '15 at 12:29