Retain old form data on validation error in Laravel

In this article, we will implement a sample form for all possible input controls and retain old data when data validation error will occur.

Before we jump into the implementation make sure you have following ready.

Alright, let’s dive into the steps.

Sample Product Form Page

Let’s first create a create product form page and the required route and controller method for the same.

Add the following entry into your route (routes / web.php) file.

Route Entry

Route::get('/oldformdata', 'OldDataController@create');

Now let’s add the supporting controller method create in Controller. We have created a separate controller for retaining old form data OlddataController.

    public function create()
    {
        return view('formolddata');
    }

and now, let’s create form old data view file named formolddata.blade.php under resources/views.

Laravel provides an old method, which can be invoked to get the data that was submitted in the previous form request. Let’s see how we can utilize the old method to populate different types of form fields.

Retaining Value of Input Text Box

<input type="text" class="form-control" id="productName" name="name" value="{{old('name')}}">

To retain a value of input text box you just need to assign the attribute value.

 

Retaining Value of Select Box

<select class="form-control" name="company">
<option value="Apple" {{ old('company') == "Apple" ? 'selected' : '' }}>Apple</option>
<option value="Google" {{ old('company') =="Google" ? 'selected' : '' }}>Google</option>
<option value="Mi" {{ old('company') == "Mi"? 'selected' : '' }}>Mi</option>
<option value="Samsung" {{ old('company') == "Samsung" ? 'selected' : '' }}>Samsung</option>
</select>

To retain the value of select option box, you need to compare the old value with the option value and if they are equal we will add a selected attribute to the options box.

Retaining Value of TextArea

<textarea type="text" class="form-control" id="productDescription" name="description" />{{old('description')}}</textarea>

To retain the value of a textarea we get the value from the old method and place it between opening and closing tags of textarea element.

Retaining Value of Radio Button


<label for="description">Product Available</label><br/>
<label class="radio-inline"><input type="radio" name="available" id="available" value="1" {{ (old('available') == '1') ? 'checked' : ''}}>Yes</label>
<label class="radio-inline"><input type="radio" name="available" id="available" value="0" {{ (old('available') == '0') ? 'checked' : ''}}> No</label> 

To retain the value of a radio button, we compare the old value with the actual value of the radio button and if they match we add a checked attribute to the element.

Retaining Value of Checkbox

<label class="checkbox-inline">
<input type="checkbox" name="features[]" value="Camera" {{ (is_array(old('features')) and in_array('Camera', old('features'))) ? ' checked' : '' }}/>Camera</label>
<label class="checkbox-inline"&gt
;<input type="checkbox" name="features[]" value="FrontCamera" {{ (is_array(old('features')) and in_array("FrontCamera", old('features'))) ? ' checked' : '' }}/>Front Camera</label>
<label class="checkbox-inline"><input type="checkbox" name="features[]" value="FingerPrint" {{ (is_array(old('features')) and in_array('FingerPrint', old('features'))) ? ' checked' : '' }}/>Finger print sensor</label>
<label class="checkbox-inline"><input type="checkbox" name="features[]" value="DualSim" {{ (is_array(old('features')) and in_array('DualSim', old('features'))) ? ' checked' : '' }}/>Dual sim</label>

To retain value of a checkbox, we check if the current value of the checkbox exists in the array provided by old method, and if yes we add the checked attribute.

 

Retaining Value of File Input

The value of a file input cannot be retained once it’s submitted and that’s the default behavior of the browser.

 

Here is how create form page looks like


@extends('layouts.app')

@section('content')
<h1>Add New Product</h1>
<hr>
<form action="/oldformdata" method="post">
{{ csrf_field() }}
<div class="form-group">
<label for="title">Product Name</label>
<input type="text" class="form-control" id="productName" name="name" value="{{old('name')}}">

</div>
<div class="form-group">
<label for="description">Product Company</label>
<select class="form-control" name="company">
<option value="Apple" {{ old('company') == "Apple" ? 'selected' : '' }}>Apple</option>
<option value="Google" {{ old('company') =="Google" ? 'selected' : '' }}>Google</option>
<option value="Mi" {{ old('company') == "Mi"? 'selected' : '' }}>Mi</option>
<option value="Samsung" {{ old('company') == "Samsung" ? 'selected' : '' }}>Samsung</option>
</select>
</div>
<div class="form-group">
<label for="description">Product Amount</label>
<input type="text" class="form-control" id="productAmount" name="amount" value="{{old('amount')}}"/>
</div>
<div class="form-group">
<label for="description">Product Available</label><br/>
<label class="radio-inline"><input type="radio" name="available" id="available" value="1" {{ (old('available') == '1') ? 'checked' : ''}}>Yes</label>
<label class="radio-inline"><input type="radio" name="available" id="available" value="0" {{ (old('available') == '0') ? 'checked' : ''}}> No</label>
</div>
<div class="form-group">
<label for="description">Product Description</label>
<textarea type="text" class="form-control" id="productDescription" name="description" />{{old('description')}}</textarea>
</div>
<div>
<label for="features">Product Features</label><br/>
<label class="checkbox-inline"><input type="checkbox" name="features[]" value="Camera" {{ (is_array(old('features')) and in_array('Camera', old('features'))) ? ' checked' : '' }}/>Camera</label>
<label class="checkbox-inline"><input type="checkbox" name="features[]" value="FrontCamera" {{ (is_array(old('features')) and in_array("FrontCamera", old('features'))) ? ' checked' : '' }}/>Front Camera</label>
<label class="checkbox-inline"><input type="checkbox" name="features[]" value="FingerPrint" {{ (is_array(old('features')) and in_array('FingerPrint', old('features'))) ? ' checked' : '' }}/>Finger print sensor</label>
<label class="checkbox-inline"><input type="checkbox" name="features[]" value="DualSim" {{ (is_array(old('features')) and in_array('DualSim', old('features'))) ? ' checked' : '' }}/>Dual sim</label>
</div>
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach

</ul>
</div>
@endif
<button type="submit" class="btn btn-primary">Submit</button>
</form>
@endsection

Now if you hit the url /oldformdata then you should see the below page.

I have already added the code in view file for retaining form old data on click of submit button if one or more data validation fails.
for this, we have to add a route in web.php

Route entry
Route::post('/oldformdata', 'OlddataController@store');

 

we have to add store method in OldDataController

public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|unique:products',
            'amount' => 'required|numeric',
            'company' => 'required',
            'available' => 'required',
            'description' => 'required',
            'features' => 'required',
           
        ]);
        
    }

 

In this controller method, We validate all the input fields of product form, if one or more data validation fails, form old data will be shown on redirect.

 

 

 

 

Demo

 
Demo

Related Articles

If you like our content, please consider buying me a coffee.

Thank you for your support!

Buy me a coffeeBuy me a coffee

Leave a reply:

Your email address will not be published.

Site Footer