Form with errors and old values

  • Steps

    1. Show validation error

    
    
    
     <form id="settings-profile" method="post" action="">
    
    
        <div class="mb-6">
            <label for="firstName" class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300">First Name</label>
    
            <input type="firstName" id="firstName" name="firstName" value=""  required>
    
            @ if($errors->has('firstName'))
                <div class="error text-red-500 text-xs">{{ $errors->first('firstName') }}</div>
           @endif
        </div>
    
        <div class="mb-6">
            <label for="lastName" class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300">Last Name</label>
    
            <input type="lastName" id="lastName" name="lastName" value=""  required>
    
            @if($errors->has('lastName'))
                <div class="error text-red-500 text-xs">{{ $errors->first('lastName') }}</div>
            @endif
        </div>
    </form>
    
    
    Laravel controller
    
    
    $request->validate([
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ]);
    
    
    if($validate->fails()) {
      return Redirect::back()->withErrors($validate);
    }
    

    2. show old form values and default form values

    
    <form id="settings-profile" method="post" action="">
    
    
    <div class="mb-6">
    
        <label for="firstName" class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300">First Name</label>
    
        <input type="firstName" id="firstName" name="firstName" value="{{old('firstName', $profile->lastName)}}" required>
    
        @if($errors->has('firstName'))
            <div class="error text-red-500 text-xs">{{ $errors->first('firstName') }}</div>
        @endif
    
    </div>
    
    <div class="mb-6">
        
        <label for="lastName" class="text-sm font-medium text-gray-900 block mb-2 dark:text-gray-300">Last Name</label>
    
        <input type="lastName" id="lastName" name="lastName" value="{{old('lastName'}}" required>
    
        @if($errors->has('lastName'))
            <div class="error text-red-500 text-xs">{{ $errors->first('lastName') }}</div>
        @endif
    
    </div>
    </form>
    
    
    In controller
    
    if($validate->fails()) {
       return Redirect::back()->withInput()->withErrors($validate);
    }
    
    In view
    
    
    @if (count($errors) > 0)
                <div class="alert alert-danger">
                    <ul>
                         @foreach ($errors->all() as $error)
                          <li>{{ $error }}</li>
                          @endforeach
                    </ul>
                </div>
                @endif