Laravel - Как устранить ошибку 500: внутренняя ошибка сервера, когда $ currenttstatus = NULL - PullRequest
0 голосов
/ 03 апреля 2020

В моем Laravel -5.8 проекте у меня есть этот код:

    public function manager_employee_goal($id)
    { 
       $userCompany = Auth::user()->company_id;
       $userEmployee = Auth::user()->employee_id;
       $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
       $linemanager = DB::table('hr_employees')->select('line_manager_id')->where('id', $userEmployee)->first();
       $linemanageremployee = DB::table('hr_employees')->select('id')->where('line_manager_id', $linemanager->line_manager_id)->pluck('id');

      $appraisedemployees = HrEmployee::select('id', 'employee_code', 'first_name', 'last_name')->where('id', $id)->get();   

       $goals = AppraisalGoal::where('employee_id', $id)->where('appraisal_identity_id', $identities->id)->where('is_published', 1)->where('id', '!=', $linemanager->line_manager_id)->get();
       $currentstatus = AppraisalGoal::select('is_approved')->where('employee_id', $id)->where('appraisal_identity_id', $identities->id)->where('is_published', 1)->where('id', '!=', $linemanager->line_manager_id)->first();
        $incompleteCount = $goals->filter(function($item) {
          return $item->is_approved == 1;
      })->count();               

       return view('appraisal.appraisal_goals.manager_employee_goal')->with('goals', $goals)->with('appraisedemployees', $appraisedemployees)->with('incompleteCount', $incompleteCount)->with('currentstatus', $currentstatus); 

   }

view

        <div class="col-md-12">
        <!-- general form elements -->
         <div class="card card-secondary">
            <div class="card-header">
                <h3 class="card-title">Goal Review</h3>
              <p class="d-flex flex-column text-right">
                <span class="font-weight-bold">
                    Current Status: 
                            @if ($currentstatus->is_approved == 3)
                                <span class="badge bg-success" >Approved</span>
                            @elseif ($currentstatus->is_approved == 2)
                                <span class="badge bg-danger">Not Approved</span>
                            @elseif ($currentstatus->is_approved == 1)
                                <span class="badge bg-info">Awaiting Approval</span>                                  
                            @else
                                <span class="badge bg-black">Draft</span>                                    
                            @endif  
                </span>
              </p>                     
            </div>
            <!-- /.card-header -->
            <!-- form start -->

<div class="card-body">
    <div class="table-responsive">
        <table class=" table table-bordered table-striped table-hover datatable">
            <thead>
                <tr>

                    <th width="8%">
                        Goal Type
                    </th>
                    <th width="20%">
                        Goal Title & Description
                    </th>
                    <th width="20%">
                    Activities
                    </th>
                    <th width="20%">
                        KPIs
                    </th>                        
                    <th width="11%">
                        Start Date - End Date
                    </th>
                    <th>
                        Weight(%)
                    </th>  
                    <th>
                        &nbsp;
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach($goals as $key => $goal)
                        <td>
                            <!--{{ $goal->goaltype ? $goal->goaltype->name : 'Uncategorized' }}-->
                            {{$goal->goaltype->name ?? '' }}
                        </td>                           
                        <td>
                            <b>{{$goal->goal_title ?? '' }}</b>
                            <br><br>
                            {!! Str::words($goal->goal_description, 20, ' ...') !!}
                        </td> 
                        <td>
                            @foreach($goal->appraisalgoaldetail as $key => $appraisalgoaldetail)
                                <ul class="list-unstyled">
                                    <li>
                                        <!--{{$key+1}}.  {{$appraisalgoaldetail->activity}}-->  
                                        {{$key+1}}.  {!! Str::words($appraisalgoaldetail->activity, 10, ' ...') !!}
                                    </li>
                                </ul>
                            @endforeach
                        </td>                             
                        <td>
                            @foreach($goal->appraisalgoaldetail as $key => $appraisalgoaldetail)
                                <ul class="list-unstyled">
                                    <li>
                                        <!--{{$key+1}}.  {{$appraisalgoaldetail->kpi_description}}-->
                                        {{$key+1}}.  {!! Str::words($appraisalgoaldetail->kpi_description, 10, ' ...') !!}
                                    </li>
                                </ul>
                            @endforeach
                        </td>

                        <td>

                            {{Carbon\Carbon::parse($goal->appraisal_start_date)->format('M d, Y') ?? '' }} - {{Carbon\Carbon::parse($goal->appraisal_end_date)->format('M d, Y') ?? '' }}
                        </td>  
                        <td>
                            {{$goal->weighted_score ?? '' }}
                        </td>                            
                        <td>          
                            @if(in_array($goal->is_approved, [1, 2, 3]))
                                <a class="btn btn-xs btn-primary" href="{{ route('appraisal.appraisal_goals.manager_employee_goal_list', ['id'=>$goal->id]) }}">
                                    {{ trans('global.view') }}
                                </a> 
                            @endif
                            @if(in_array($goal->is_approved, [1]))
                                <a class="btn btn-xs btn-info" data-toggle="modal" data-target="#comment{{ $goal->id }}"   data-original-title="Comment">Comment</a>
                            @endif                             

                        </td>                           
                </tr>
                @endforeach 
            </tbody>
        </table>
    </div>

    <div class="row no-print">
        <div class="col-12">
          @if ($incompleteCount)
              &nbsp;&nbsp;&nbsp;<a href ="{{ route('appraisal.appraisal_goals.manager_employee_all_goal_approve', ['id' => $goal->employee_id])}}" class="btn btn-primary float-left"><i class="fas fa-check"></i> Approve</a>

              <a href ="{{ route('appraisal.appraisal_goals.manager_employee_all_goal_reject', ['id' => $goal->employee_id])}}" class="btn btn-danger"><i class="fas fa-minus-circle"></i> Reject</a>                 
          @endif 
        </div>       
    </div>        
</div>             

    </div>
   </div>

Когда я захотел загрузить страницу, я получил эту ошибку:

Ошибка 500: внутренняя ошибка сервера

Однако, когда я

d ie (var_dump ($ incompleteCount));

Я получил

int (0)

и

d ie (var_dump ($ currenttstatus));

Я получил

NULL

Наконец, когда я удалил:

                    Current Status: 
                            @if ($currentstatus->is_approved == 3)
                                <span class="badge bg-success" >Approved</span>
                            @elseif ($currentstatus->is_approved == 2)
                                <span class="badge bg-danger">Not Approved</span>
                            @elseif ($currentstatus->is_approved == 1)
                                <span class="badge bg-info">Awaiting Approval</span>                                  
                            @else
                                <span class="badge bg-black">Draft</span>                                    
                            @endif  

из блейда вида, ошибка исчезла.

Как мне решить эту проблему?

Спасибо

1 Ответ

0 голосов
/ 03 апреля 2020

@ AndySong указал на проблему, вы пытаетесь получить свойство с нулевым значением.

Пара решений:

  1. Если вы не можете найти текущий статус, следует страница все еще загружается? Если нет, используйте firstOrFail():

Пример -

$currentstatus = AppraisalGoal::select('is_approved')
    ->where('employee_id', $id)
    ->where('appraisal_identity_id', $identities->id)
    ->where('is_published', 1)
    ->where('id', '!=', $linemanager->line_manager_id)
    ->firstOrFail();
Измените ваши операторы if для текущего статуса, чтобы проверить, является ли текущий статус нулевым:

Пример -

Current Status: 
@if (is_null($currentstatus))
    <span class="badge bg-black">Draft</span> 
@elseif ($currentstatus->is_approved == 3)
    <span class="badge bg-success" >Approved</span>
@elseif ($currentstatus->is_approved == 2)
    <span class="badge bg-danger">Not Approved</span>
@elseif ($currentstatus->is_approved == 1)
    <span class="badge bg-info">Awaiting Approval</span>                                  
@else
    <span class="badge bg-black">Draft</span>                                    
@endif  
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...