Home > Back-end >  What's the best way / best practice to handle boolean in a Laravel 8 Request class?
What's the best way / best practice to handle boolean in a Laravel 8 Request class?

Time:10-06

I have some standard single checkboxes that define a specific boolean value, i.e. is_active

 <label class="form-check-label text-google">
   <input type="checkbox" name="is_active" id="is_active" value="1" class="form-check-input"
      @if (old('is_active') == '1' || (empty(old()) && $doctor->is_active == 1)) checked @endif>
      {{ __('Doctor activated') }}
      <i class="input-helper"></i>
 </label>

When sending it to my Controller the request runs through a custom Request class, where I currently do the following. Mainly important for the updating method, so deselected checkbox will be updated in the database.

  /**
  * Get the validation rules that apply to the request.
  *
  * @return array
  */
  public function rules()
 {
   $this->request->set("is_active", $this->request->has("is_active"));

   return [ ...

I also casted the is_active property in the Model as boolean value. What is best practice here? I couldn't find anything that leads me in the right direction...

Thanks in advance.

CodePudding user response:

Since you want to touch the request before the validation, you could make use of this method: prepareForValidation():

Prepare Input For Validation

If you need to prepare or sanitize any data from the request before you apply your validation rules, you may use the prepareForValidation method:

use Illuminate\Support\Str;

/**
 * Prepare the data for validation.
 *
 * @return void
 */
protected function prepareForValidation()
{
    $this->merge([
        'slug' => Str::slug($this->slug),
    ]);
}

So in your case you can do:

public function prepareForValidation()
{
    $this->merge([
        'is_active' => $this->request->has('is_active')),
    ]);
}

CodePudding user response:

as i read you want to know if there is a value or not, in fact i think you can use the class Request filled function.

  • Related