Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this tutorial, I will give you an example of How to Retain old form data on validation error in Laravel, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application. Sometimes we need to use this functionality when we have a bigger form to fill up and we have multiple fields to input data, We input wrong data many times in input types.
First, what we’re doing here, This is the example :
For Example, we have a field name price and we input text in the price field and we only used validation rules in the controller for number or required for request parameters and we are not using any type of frontend validation in the Laravel application.
When we click the save button to submit our form, the page will be refresh or reload, and the controller gives us a validation message because we input text in the price field and we already write validation rules to validate the request parameters, and our all form data will be removed which data we filled in other input fields, This is very painful for every user to fill all the fields again and again.
To remain old values data after page reload in Laravel, we use {{old(‘input_name’)}} in our blade file.
php artisan make:migration create_products_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name',25);
$table->double('price',8,2);
$table->string('state_delivery_code',25);
$table->string('short_description',25);
$table->longText('full_description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
php artisan:migrate
php artisan make:model Model/Product
app\Model\Product
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $table = 'products';
protected $fillable = ['name','price','state_delivery_code','short_description','full_description'];
}
routes/web.php
Route::get('add-product','ProductController@create')->name('add.product');
Route::post('store-product','ProductController@store')->name('store.product');
php artisan make:controller ProductController
app\Http\Controllers\ProductController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Model\Product;
class ProductController extends Controller
{
public function create(){
return view('create');
}
public function store(Request $request){
#Validate Request with custom Messages
$this->validate($request, [
'product_name' => 'required',
'product_price'=> 'required|numeric',
'state_code' => 'required',
'short_description' => 'required',
'full_description' => 'required',
],
['product_name.required' => 'The : Product name field can not be empty value.',
'product_price.required' => 'The : Product price field can not be empty value.',
'state_code.required' => 'The : Product state Code field can not be empty value.',
'short_description.required' => 'The : Product short description field can not be empty value.',
'full_description.required' => 'The : Product Full description field can not be empty value.']);
$data = new Product();
$data->name = $request->product_name;
$data->price = $request->product_price;
$data->state_delivery_code = $request->state_code;
$data->short_description = $request->short_description;
$data->full_description = $request->full_description;
$data->save();
dd('success');
}
}
resources\views\create.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>How to Retain old form data on validation error in Laravel 8 | www.8bityard.com</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="col-sm-4 float-right">
@if ($errors->any())
@foreach ($errors->all() as $error)
<div class="alert alert-danger alert-dismissible p-2">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Error!</strong> {{$error}}.
</div>
@endforeach
@endif
</div>
<h3>Laravel - Retain old form data on validation error | After Page Reload.</h3>
<div class="card">
<form method="post" action="{{route('store.product')}}">
@csrf
<div class="card-header">Please fill up all the Field's.</div>
<div class="card-body">
<div class="row">
<div class="col-md-4">
<label><b>{{ __('Product Name') }}</b><span style="color:red">*</span></label>
<input type="text" class="form-control" name="product_name" value="{{old('product_name')}}" placeholder="Enter Product name">
</div>
<div class="col-md-4">
<label><b>{{ __('Product Price') }}</b><span style="color:red">*</span></label>
<input type="text" class="form-control" name="product_price" value="{{old('product_price')}}" placeholder="Enter Product price">
</div>
<div class="col-md-4">
<label><b>{{ __('State Delivery Code') }}</b><span style="color:red">*</span></label>
<input type="text" class="form-control" name="state_code" value="{{old('state_code')}}" placeholder="Enter Product Delivery code">
</div>
<div class="col-md-6">
<label><b>{{ __('Short Description') }}</b><span style="color:red">*</span></label>
<textarea class="form-control" name="short_description" placeholder="Please Enter Product Short Description..." rows="3" cols="50">{{old('short_description')}}</textarea>
</div>
<div class="col-md-6">
<label><b>{{ __('Full Description') }}</b><span style="color:red">*</span></label>
<textarea class="form-control" name="full_description" placeholder="Please Enter Product Complete Description..." rows="3" cols="50">{{old('full_description')}}</textarea>
</div>
</div>
</div>
<div class="col-md-3">
<button type="submit" class="btn btn-block btn-info btn-sm">Save</button>
</div>
</div>
</form>
</div>
</body>
</html>
<input type="text" name="product_price" value="{{old('product_price')}}">
I will give you a quick tip, for how you can use Retain old form data on validation error in Select Box, Radio Button, and Checkbox in blade file in Laravel.
<select name="phone">
<option value="Apple" {{ old('phone') == "Apple" ? 'selected' : '' }}>Apple</option>
<option value="Samsung" {{ old('phone') == "Samsung" ? 'selected' : '' }}>Samsung</option>
<option value="Mi" {{ old('phone') == "Mi" ? 'selected' : '' }}>Mi</option>
</select>
To retain the value of the 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.
<label for="gender">Select Gender</label>
<input type="radio" name="gender" value="m" {{ (old('gender') == 'm') ? 'checked' : ''}}>Male
<input type="radio" name="gender" value="f" {{ (old('gender') == 'f') ? 'checked' : ''}}>Female
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.
<label for="fruits">Check The fruits</label>
<input type="checkbox" name="fruit[]" value="Apple" {{ (is_array(old('fruit')) and in_array('Apple', old('fruit'))) ? ' checked' : '' }}/>Apple</label>
<input type="checkbox" name="fruit[]" value="Grape" {{ (is_array(old('fruit')) and in_array("Grape", old('fruit'))) ? ' checked' : '' }}/>Grape</label>
<input type="checkbox" name="fruit[]" value="Mango" {{ (is_array(old('fruit')) and in_array("Mango", old('fruit'))) ? ' checked' : '' }}/>Mango</label>
To retain the value of a checkbox, we check if the current value of the checkbox exists in the array provided by the old method and if yes we add the checked attribute.
In this article, we learned “How to Retain old form data on validation error in Laravel”, I hope this article will help you with your Laravel application Project.