【问题标题】:E_NOTICE Undefined index: respondent_id in LaravelE_NOTICE 未定义索引:Laravel 中的 respondent_id
【发布时间】:2020-08-22 19:10:25
【问题描述】:

我正在尝试在我的 Laravel-5.8 应用程序中创建动态表单输入数组。

这是我的代码。

型号

class AppraisalRespondent extends Model
{
    protected $table = 'appraisal_respondents';

    protected $primaryKey = 'id';

    protected $fillable = [
              'id',
              'respondent_id',
              'department_id',
              'company_name',
              'respondent_date',
          ];

    public function employeerespondent()
    {
        return $this->belongsTo('App\Models\Hr\HrEmployee','respondent_id');
    }

    public function department()
    {
        return $this->belongsTo('App\Models\Hr\HrDepartment','department_id','id');
    }  
}

我也使用请求规则进行验证

规则请求

class StoreAppraisalRespondentRequest extends FormRequest
{
    public function rules()
    {
        return [
            'respondent_id.*' => [
                'required', 
                Rule::unique('appraisal_respondents')->where(function ($query) {
               return $query->where('appraisal_identity_id', $this->appraisal_identity_id)
                    ->where('respondent_id', $this->respondent_id)
                  ->where('employee_id', $this->employee_id);
            })               
            ],
            'department_id.*' => [
                 'required', 
            ],

            'respondent_date.*' => [
                'required', 
                'date',
                'date_format:d-m-Y',
            ],

        ];
    }  

 }

控制器

  public function store(StoreAppraisalRespondentRequest $request)
  {
      try {      
      $input = $request->all();
      $condition = $input['respondent_id'];
      foreach ($condition as $key => $condition) {
        $emprespondent = new AppraisalRespondent;
        $emprespondent->respondent_id = $input['respondent_id'][$key];
        $emprespondent->department_id = $input['department_id'][$key];
        $emprespondent->respondent_date = $input['respondent_date'][$key];         
        $emprespondent->save();
     }
     Session::flash('success', 'Appraisal Respondent(s) created successfully');
     return redirect()->route('appraisal.appraisal_respondents.index');        
        
    } catch (Exception $ex) {
            Session::flash('error', 'Action failed! Please try again');
            return redirect()->route('appraisal.appraisal_respondents.index');
    }         
}

查看

      <form  action="{{route('appraisal.appraisal_respondents.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
           {{csrf_field()}}
        <div class="card-body">
            <div class="table-responsive">
                     <table class=" table table-bordered table-striped table-hover datatable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Respondent<span style="color:red;">*</span></th>
                                    <th>Department<span style="color:red;">*</span></th>
                                    <th>Date<span style="color:red;">*</span></th>
                                    <th scope="col" width="8%"><input type="button" class="btn btn-info addRow" value="+ Add"></th>
                                </tr>
                            </thead> 
                            <tbody class="resultbody">
                                <tr>
                                    <td class="no">1</td>
                                    <td>
                                        <select class="form-control select2bs4" data-placeholder="Choose Respondent" tabindex="1" name="respondent_id[]" style="width: 100%;">
                                            <option value="0" selected="true" disabled="true">Select Respondent</option>
                                            @if($employeerespondents->count() > 0)
                                                @foreach($employeerespondents as $employeerespondent)
                                                    <option value="{{$employeerespondent->id}}">{{$employeerespondent->employee_code}} - {{$employeerespondent->first_name}} {{$employeerespondent->last_name}}</option>
                                                @endforeach
                                            @endif
                                        </select>                                        
                                    </td>
                                    <td>
                                        <select class="form-control select2bs4" data-placeholder="Choose Respondent" tabindex="1" name="department_id[]" style="width: 100%;">
                                            <option value="0" selected="true" disabled="true">Select Department</option>
                                            @if($departments->count() > 0)
                                                @foreach($departments as $department)
                                                    <option value="{{$department->id}}">{{$department->dept_name}}</option>
                                                @endforeach  
                                            @endif
                                        </select>                                         
                                    </td>
                                    <td>
                                    <div class="input-group">
                                    <div class="input-group-prepend">
                                      <span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
                                    </div>                                         
                                       <input type="text" class="form-control respondent_date" placeholder="dd/mm/yyyy" readonly autocomplete="off" name="respondent_date[]">
                                    </div>  
                                    </td>                                    
                                    <td>
                                        <input type="button" class="btn btn-danger" value="x">
                                        <!--<a class="btn btn-danger remove"> <i class="fa fa-times"></i></a>-->
                                    </td>                                        
                                </tr>

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

Javascript

<script type="text/javascript">
    $(function () {
        $('.addRow').click(function () {
            var n = ($('.resultbody tr').length - 0) + 1;
            var tr = '<tr><td class="no">' + n + '</td>' +
                    '<td><select class="form-control select2bs4" data-placeholder="Choose Respondent" tabindex="1" name="respondent_id[]" style="width: 100%;"><option value="0" selected="true" disabled="true">Select Respondent</option>@if($employeerespondents->count() > 0)@foreach($employeerespondents as $employeerespondent)<option value="{{$employeerespondent->id}}">{{$employeerespondent->employee_code}} - {{$employeerespondent->first_name}} {{$employeerespondent->last_name}}</option>@endforeach  @endif</select>  </td>'+
                    '<td><select class="form-control select2bs4" data-placeholder="Choose Respondent" tabindex="1" name="department_id[]" style="width: 100%;"><option value="0" selected="true" disabled="true">Select Department</option>@if($departments->count() > 0)@foreach($departments as $department)<option value="{{$department->id}}">{{$department->dept_name}}</option>@endforeach  @endif</select>  </td>'+
                    '<td><div class="input-group"><div class="input-group-prepend"><span class="input-group-text"><i class="far fa-calendar-alt"></i></span></div><input type="text" class="form-control respondentDate" placeholder="dd/mm/yyyy" readonly autocomplete="off" name="respondent_date[]"></div> </td>'+
                    '<td><input type="button" class="btn btn-danger delete" value="x"></td></tr>';
            $('.resultbody').append(tr);
        });

        $('.resultbody').delegate('.delete', 'click', function () {
            $(this).parent().parent().remove();
        });

    $('body').on('focus',".respondentDate", function(){
        $(this).datepicker(
        {                    
           dateFormat: 'dd-mm-yy', 
           changeMonth: true,
           changeYear: true,
           showAnim: 'slideDown',
           duration: 'fast',
           yearRange: new Date().getFullYear() + ':' + new Date().getFullYear(),
        });
    });            

    });
  </script>

在视图中,您会注意到当用户单击“添加”时会出现一个按钮,它会添加新行

当我提交时,我收到了这个错误:

未定义索引:responent_id

它指向控制器中的这一行:

$condition = $input['respondent_id'];

我该如何解决?

谢谢

当我将控制器代码更改为:

        foreach ($request->respondent_id as $key => $respondent_id){

    $insert_array = [
            'respondent_id'                         => $request->respondent_id[$key],
            'department_id'                         => $request->department_id[$key],                
            'respondent_date'                       => $request->respondent_date[$key],
            'company_id'                            => Auth::user()->company_id,
            'created_by'                            => Auth::user()->id,
            'created_at'                            => date("Y-m-d H:i:s"),
            'is_active'                             => 1
        ];

        AppraisalRespondent::create($insert_array );

         }

我在错误日志中得到了这个:

[2020-08-22 10:42:10] production.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'respondent_id.0' in 'where clause' (SQL: select count(*) as aggregate from `appraisal_respondents` where `respondent_id`.`0` = 1 and (`appraisal_identity_id` is null and `respondent_id` = 1 and `employee_id` is null)) {"userId":469,"exception":"[object] (Illuminate\\Database\\QueryException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'respondent_id.0' in 'where clause' (SQL: select count(*) as aggregate from `appraisal_respondents` where `respondent_id`.`0` = 1 and (`appraisal_identity_id` is null and `respondent_id` = 1 and `employee_id` is null)) at C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php:664, Doctrine\\DBAL\\Driver\\PDOException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'respondent_id.0' in 'where clause' at C:\\xampp\\htdocs\\myapp\\vendor\\doctrine\\dbal\\lib\\Doctrine\\DBAL\\Driver\\PDOConnection.php:63, PDOException(code: 42S22): SQLSTATE[42S22]: Column not found: 1054 Unknown column 'respondent_id.0' in 'where clause' at C:\\xampp\\htdocs\\myapp\\vendor\\doctrine\\dbal\\lib\\Doctrine\\DBAL\\Driver\\PDOConnection.php:61)
[stacktrace]
#0 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php(624): Illuminate\\Database\\Connection->runQueryCallback('select count(*)...', Array, Object(Closure))
#1 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Connection.php(333): Illuminate\\Database\\Connection->run('select count(*)...', Array, Object(Closure))
#2 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php(2130): Illuminate\\Database\\Connection->select('select count(*)...', Array, false)
#3 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php(2118): Illuminate\\Database\\Query\\Builder->runSelect()
#4 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php(2604): Illuminate\\Database\\Query\\Builder->Illuminate\\Database\\Query\\{closure}()
#5 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php(2119): Illuminate\\Database\\Query\\Builder->onceWithColumns(Array, Object(Closure))
#6 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php(2531): Illuminate\\Database\\Query\\Builder->get(Array)
#7 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php(2459): Illuminate\\Database\\Query\\Builder->aggregate('count', Array)
#8 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Validation\\DatabasePresenceVerifier.php(55): Illuminate\\Database\\Query\\Builder->count()
#9 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Validation\\Concerns\\ValidatesAttributes.php(755): Illuminate\\Validation\\DatabasePresenceVerifier->getCount('appraisal_respo...', 'respondent_id.0', '1', NULL, 'id', Array)
#10 C:\\xampp\\htdocs\\myapp\\vendor\\laravel\\framework\\src\\Illuminate\\Validation\\Validator.php(398): Illuminate\\Validation\\Validator->validateUnique('respondent_id.0', '1', Array, Object(Illuminate\\Validation\\Validator))

但该列在那里。

【问题讨论】:

  • @DigitalDrifter - 我该怎么做才能解决它?
  • 拜托,你能提供$input的调试吗?我认为您选择的名称不正确。
  • @S.LT - 我已经更新了我的代码
  • 好的,我看到很多语法错误,让我有时间写一个答案,希望能让你找到解决方案。

标签: javascript laravel


【解决方案1】:

我将使用您共享的循环,同时稍微更正一下语法。如果你想要一些“功能性”的东西,如果你的观点和形式是正确的,你应该尝试一下:

$inputs = $request->all(); // that give you an array, you can iterate
foreach ($inputs as $input){

    print_r($input); // that should give you:
    /*[
        'respondent_id'    => 'value_respondent_id',
        'department_id'    => 'value_department_id',                
        'respondent_date'  => 'value_respondent_date',
    ]*/
    // You can add what you want or create object or do action
}

我不想用AppraisalRespondent::create($insert_array); 做什么。我认为你需要一些知识来实现​​你想要的。为了做你想做的事,你需要这些资源:

这可能是一个好的开始。

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 2019-03-21
    • 2011-03-16
    • 2018-08-02
    • 2012-08-24
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多