0

Using Laravel-5.8, I am trying to delevop a web application.I have two tables: goals and goal_details. Goal is the main model class.

Using Rules and Request in Laravel:

public function rules()
{
    return [
        'goal_title'                => 'required|min:5|max:100',
        'goal_type_id'              => 'required',
        'weighted_score'            => 'required|numeric|min:0|max:500',           
        'start_date'                => 'required',
        'end_date'                  => 'required|after_or_equal:start_date',
        'kpi_description'           => 'required',
        'activity'                  => 'required',
    ];
}

goals: customer_id, goal_title, weighted_score, start_date, end_date

goal_details: goal_type_id, kpi_description

public function create()
{
    $userCompany = Auth::user()->company_id;
    $identities = DB::table('appraisal_identity')->select('id','appraisal_name')->where('company_id', $userCompany)->where('is_current', 1)->first();       
    $goaltypes   =       GoalType::where('company_id', $userCompany)->get(); 
     $categories = GoalType::with('children')->where('company_id', $userCompany)->whereNull('parent_id')->get();

    return view('goals.create')
            ->with('goaltypes', $goaltypes)
            ->with('categories', $categories)
            ->with('identities', $identities);
}
public function store(StoreGoalRequest $request)
{
    $startDate = Carbon::parse($request->start_date);
    $endDate = Carbon::parse($request->end_date);
    $userCompany = Auth::user()->company_id;
    $employeeId = Auth::user()->employee_id;
        $goal = new Goal();
        $goal->goal_type_id             = $request->goal_type_id;
        $goal->appraisal_identity_id    = $request->appraisal_identity_id;
        $goal->employee_id              = $employeeId;
        $goal->weighted_score           = $request->weighted_score;
        $goal->goal_title               = $request->goal_title;
        $goal->goal_description         = $request->goal_description;
        $goal->start_date               = $startDate;
        $goal->end_date                 = $endDate;
        $goal->save();


        foreach ( $request->activity as $key => $activity){
            $goaldetail = new GoalDetail();
            $goaldetail->kpi_description            = $request->kpi_description[$key];
            $goaldetail->activity                   = $request->activity[$key];
            $goaldetail->appraisal_goal_id          = $goal->id;
            $goaldetail->save();
         }

            Session::flash('success', 'Goal is created successfully');
            return redirect()->route('goals.index');
}

create.blade.php

<div class="row">
        <div class="col-md-12">
        <!-- general form elements -->
         <div class="card card-secondary">
            <!-- /.card-header -->
            <!-- form start -->
          <form  method="POST" action="{{route('goals.store')}}">
          @csrf
       <div class="card-body">
        <div class="form-body">
        <div class="row">
            
          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
              <select id="goal_type" class="form-control" name="goal_type_id">
                <option value="">Select Goal Type</option>

                @foreach ($categories as $category)
                @unless($category->name === 'Job Fundamentals')
                  <option disabled="disabled" value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>

                  @if ($category->children)
                    @foreach ($category->children as $child)
                    @unless($child->name === 'Job Fundamentals')
                      <option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}>&nbsp;&nbsp;{{ $child->name }}</option>
                    @endunless
                    @endforeach
                  @endif
                  @endunless
                @endforeach
              </select>
            </div>
          </div>    
            
          <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Goal Title:<span style="color:red;">*</span></label>
              <input  type="text" name="goal_title" placeholder="Enter goal title here" class="form-control">
            </div>
          </div>
            
          <div class="col-sm-12">
            <div class="form-group">
                <label>Goal Description</label>
                <textarea rows="2" name="goal_description" class="form-control" placeholder="Enter Goal Description here ..."></textarea>
            </div>
          </div>

<div class="col-sm-12">
            <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th scope="col">Activity<span style="color:red;">*</span></th>
                            <th scope="col">KPI Description<span style="color:red;">*</span></th>
                            <th scope="col">Attachment</th>
                            <th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td><input type="text" name="activity[]" class="form-control activity" ></td>
                            <td><input type="text" name="kpi_description[]" class="form-control kpi" ></td>
                            <td>
                                <div class="custom-file">
                                <input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile">
                                <label class="custom-file-label" for="exampleInputFile">Choose file</label>
                                </div>
                            </td>
                            <td><a class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>
                         </tr>
                        </tbody>


                    </table>
        </div>
          <div class="col-12 col-sm-4">
            <div class="form-group">
              <label class="control-label"> Weight:</label>
              <input  type="number" name="weighted_score" placeholder="Enter weighted score here" class="form-control">
            </div>
          </div>  

          <div class="col-12 col-sm-4">
            <div class="form-group">
              <label class="control-label"> Start Date:<span style="color:red;">*</span></label>
              <input type="date" class="form-control" placeholder="dd/mm/yyyy" name="start_date"  min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
            </div>
          </div>

          <div class="col-12 col-sm-4">
            <div class="form-group">
              <label class="control-label"> End Date:<span style="color:red;">*</span></label>
              <input type="date" class="form-control" placeholder="dd/mm/yyyy" name="end_date"  min="{{Carbon\Carbon::now()->format('Y-m-d')}}">
            </div>
          </div>

       </div>
     </div>
    </div>          
    <!-- /.card-body -->
    <div class="card-footer">
      <button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
      <button type="button" onclick="window.location.href='{{route('appraisal.appraisal_goals.index')}}'" class="btn btn-default">Cancel</button>
    </div>           
       
    </form>
    </div>
    <!-- /.card -->
   </div>
   <!--/.col (left) -->
  </div>

javascript

<script type="text/javascript">
    $(document).ready(function(){
        $('.addRow').on('click', function () {
   var isHod = {{ Auth::user()->is_hod == 0 ? 0 : 1 }};
    var numRows = $('.activity').length

    if (isHod || (!isHod && numRows<3)) {
        addRow();
    }
        });

        function addRow() {
            var addRow = '<tr>\n' +
' <td><input type="text" name="activity[]" class="form-control activity" ></td>\n' +
'   <td><input type="text" name="kpi_description[]" class="form-control kpi_description" ></td>\n' +
' <td><div class="custom-file"><input type="file" name="appraisal_doc[]" class="custom-file-input" id="customFile"><label class="custom-file-label" for="exampleInputFile">Choose file</label></div></td>\n' +
'  <td><a   class="btn btn-danger remove"> <i class="fa fa-times"></i></a></td>\n' +
'    </tr>';
            $('tbody').append(addRow);
            addRemoveListener();
        };
       addRemoveListener();
    });

function addRemoveListener() {
$('.remove').on('click', function () {
        var l =$('tbody tr').length;
        if(l==1){
            alert('you cant delete last one')
        }else{

            $(this).parent().parent().remove();

        }

    });
  }

</script>

When I submitted, I observed that the fields from goal_details: goal_type_id, kpi_description are not validated as required. It allows null. But all fields in goals are validated.

How do I resolve this?

Thank you.

2 Answers 2

0

Check if it can solve your "kpi_description" validation problem :

public function rules()
{
    return [
        'goal_title'                => 'required|min:5|max:100',
        'goal_type_id'              => 'required',
        'weighted_score'            => 'required|numeric|min:0|max:500',           
        'start_date'                => 'required',
        'end_date'                  => 'required|after_or_equal:start_date',
        'kpi_description'           => 'required|array',
        'kpi_description.*'         => 'required',
        'activity'                  => 'required',
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

0

after defining rules you have to call "validated" method as needed. try this :

public function store(StoreGoalRequest $request)
{
    $validated = $request->validated();
    $startDate = Carbon::parse($request->start_date);
    $endDate = Carbon::parse($request->end_date);
    $userCompany = Auth::user()->company_id;
    $employeeId = Auth::user()->employee_id;
        $goal = new Goal();
        $goal->goal_type_id             = $request->goal_type_id;
        $goal->appraisal_identity_id    = $request->appraisal_identity_id;
        $goal->employee_id              = $employeeId;
        $goal->weighted_score           = $request->weighted_score;
        $goal->goal_title               = $request->goal_title;
        $goal->goal_description         = $request->goal_description;
        $goal->start_date               = $startDate;
        $goal->end_date                 = $endDate;
        $goal->save();


        foreach ( $request->activity as $key => $activity){
            $goaldetail = new GoalDetail();
            $goaldetail->kpi_description            = $request->kpi_description[$key];
            $goaldetail->activity                   = $request->activity[$key];
            $goaldetail->appraisal_goal_id          = $goal->id;
            $goaldetail->save();
         }

            Session::flash('success', 'Goal is created successfully');
            return redirect()->route('goals.index');
}

2 Comments

if it didn't help let me see your form, please .
It didn't work. So I've added the form as requested. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.