16372

Laravel - validation rule for date on update

I have this validation rule:

'event_start' => 'required|date|after:today',

and on creating a model all is fine, this date cannot be before today....

but when a user tries to update the event start date is before today and a validation error pops up....is there a way to adjust this for updating the model? So that when a user updates this rule checks only if it is a date?

UPDATE

this is my only validation check for both create and update:

<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class EventsForm extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { if( auth()->check() ) return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'title' => 'required|min:2|max:255', 'event_start' => 'required|date|after:today', ]; return $rules; } }

Answer1:

You should have different form request classes for creating and updating events. That’s not to say you can’t use inheritance, though.

If your update method only slightly differs from the create method, then you could extend that method’s form request and amend the rules for update:

class CreateEventRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'name' => 'required|unique:events',
            'start_date' => 'required|date|after:today',
            'door_time' => 'required|date_format:"H:i:s",
            'location' => 'required',
        ];
    }
}


And…

class UpdateEventRequest extends CreateEventRequest
{
    public function rules()
    {
        // Get ID of event if using route–model binding
        $id = $this->route('event')->getKey();

        // Use array merge to override create event form request’s rules
        return array_merge(parent::rules(), [
            'name' => 'required|unique:events,name,'.$id,
            'start_date' => 'required|date',
        ]);
    }
}


You could even push the rules method to an abstract class, and have your create and update form request classes extend that class:

abstract class EventFormRequest extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        // Base event rules
    }
}

class CreateEventRequest extends EventFormRequest
{
    public function rules()
    {
        // Create-specific rules
    }
}

class UpdateEventRequest extends EventFormRequest
{
    public function rules()
    {
        // Update-specific rules
    }
}

    

Answer2:

If create and update logic is different, just use different validation rules for each method:

'event_start' => 'required|date|after:today', // For creating 'event_start' => 'required|date', // For updating

Answer3:

I assume the validation rule is located on HttpRequest, then you could change the validation rule to be:

'event_start' => 'required|date',

And on your controller:

public function store(EventRequest $request) { $validator = Validator::make($request->all(), [ 'event_start' => 'date|after:today', ]); if($validator->fails()) { return redirect('event/create') ->withErrors($validator) ->withInput(); } // Save the event }

Answer4:

I think you have common insert and update method, in this case make two different validation like:

post a value in hidden field that define if it's a insert request or a update

if($req_type == 'insert') { 'event_start' => 'required|date|after:today', // For creating } else if($req_type == 'update') { 'event_start' => 'required|date', // For updating }

Answer5:

use the single method of rules to check if create or update and return array based on that

public function rules() { $rules = [ 'title' => 'required|min:2|max:255', 'event_start' => 'required|date|after:today', ]; // $this->route('event') will be null if its create so the defualt one is ok if($this->route('event')) { // modify rules for edit here $rules['event_start'] => 'required|date'; $rules['name'] => 'required|unique:events,name,'.$this->route('event')->id; // above rules will only be applied if update. } return $rules; }

Recommend

  • Haskell: Yesod and state
  • Implicit declaration of function 'sum' is invalid in C99
  • Monotouch - Issue with QLPreviewController
  • Turn off Zurb Foundation 5 meta tags
  • Payum Bundle : How to change the view of capture action in symfony2
  • Laravel request validation throwing HttpResponseException in version 5.2
  • TFS Build notification options not populating build definitions
  • How to fetch the file list from gcs?
  • Swift 3 Custom extension of ns measurement? Ex. Sheeps to goats
  • Display Current Video in Windows Phone 8 using AudioVideoCaptureDevice?
  • Error when trying to send an email using Gmail API in Java
  • How to authenticate user name and password against Active Directory Federation Services (ADFS)?
  • Django: DRY principle and UserPassesTestMixin
  • Deleting a widget from QTableView
  • multidatatrigger with multibinding in ControlTemplate.Triggers
  • Is there a parser equivalent of 'fragment' marking in ANTLR4?
  • Django return user model id with L
  • Laravel: Getting Session ID oddly truncates when using foreach
  • Build Successful but not running on simulator
  • Different response to non-authenticated users and AJAX calls
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Symfony2: How to get request parameter
  • Cannot Parse HTML Data Using Android / JSOUP
  • log4net write single file for each call to log.info
  • Getting error when using KSoap library to consume .NET web services
  • JTable with a ScrollPane misbehaving
  • Java static initializers and reflection
  • unknown Exception android
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Binding checkboxes to object values in AngularJs
  • Observable and ngFor in Angular 2
  • How can I use `wmic` in a Windows PE script?
  • failed to connect to specific WiFi in android programmatically
  • Unable to use reactive element in my shiny app
  • Net Present Value in Excel for Grouped Recurring CF
  • How to push additional view controllers onto NavigationController but keep the TabBar?
  • How can I use threading to 'tick' a timer to be accessed by other threads?
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?