Laravel form requests and form validation

Below is my solution for using a single form validation request for the create / store and edit / update methods on the controller (Laravel 5).

This is a cumbersome and ugly hack (i.e., it reads the URI segments to get the identifier of the record being edited). Is there a better way to determine if a request receives information from an edit / update request? (without direct pass $ id and flag to request)

/**
 * Sets the basic validation rules that apply to the request.
 *
 * @return array
 */
protected $rules = [    
        'trading_name' => 'required|min:3|max:50|unique:companies',
        'legal_name' => 'required|min:3|max:50|unique:companies',
        'legal_identifier' => 'required|min:3|max:50|unique:companies',
        'status' => 'required',
        'website' => 'active_url',
        'type' => 'required',
        'payment_terms' => 'required|integer|min:0|max:180',
        'credit_limit' => 'required|integer|min:0|max:500000',
        'notes' => 'max:2000',
];

/**
 * Sets addition validation rules depending on the request type (i.e. edit & update).
 * 
 * 
 * @return array
 */
public function rules()
{
    $rules = $this->rules;
    if ($this->is('companies/*') == true) #Add a ignore self-unique rule as this is a edit&update request
    {
        $id = $this->segment(2);
        $rules['trading_name'] = $rules['trading_name'].',trading_name,'.$id;
        $rules['legal_name'] = $rules['legal_name'].',legal_name,'.$id;
        $rules['legal_identifier'] = $rules['legal_identifier'].',legal_identifier,'.$id;
    }
    return $rules;
}
+4
source share
2 answers

- -

public function rules()
{
    if($request()->isMethod('put'))
    {
         // Update rules here
    }

    return $this->rules;
}
+3

, Google; https://laracasts.com/discuss/channels/requests/laravel-5-validation-request-how-to-handle-validation-on-update

( )

  • $id = $this- > route() → parameters() [ "companies" ];
  • $id = $this- > route() → getParameter ('');
  • $id = $this- > route ('');
  • $id = $this- >
+2

All Articles