GOOGLE ADS

суббота, 9 апреля 2022 г.

Неопределенная переменная в проекте Laravel 8 (php 7.4)

Большинство функций в проекте работают, но когда дело доходит до регистрации результатов, я получаю сообщение об ошибке.

Это обширная система соревнований по стрельбе из пистолета, в которой администраторы могут создавать соревнования различных видов. Стрелки могут зарегистрироваться и записаться на соревнования. По окончании соревнований результаты вводятся в систему. Вот когда появляется проблема.

Система обновлена ​​с Laravel 5.3 до 8 и отлично работает в 5.3. Вот работающая тестовая система 5.3: https://test.webshooter.se

Неопределенная переменная: патрулирует Ошибка:

 [2022-02-20 14:14:12] local.ERROR: Undefined variable: patrols {"userId":1,"exception":"[object] (ErrorException(code: 0): Undefined variable: patrols at /Users/ralph/laravel9/webshooter_web/app/Repositories/ResultsRepository.php:156)

Возможный тип_патруля: ноль, финал, различение. В данном случае это тип null.

Это часть PatrolRepository.php, где возникает ошибка:


public function getPatrols($competitionsId)
{
if (!$this->request->has('patrol_type')):
$patrols = Patrol::where('competitions_id', $competitionsId)->orderBy('sortorder')->get();
elseif ($this->request->get('patrol_type') == 'finals'):
$patrols = PatrolFinals::where('competitions_id', $competitionsId)->orderBy('sortorder')->get();
elseif ($this->request->get('patrol_type') == 'distinguish'):
$patrols = PatrolDistinguish::where('competitions_id', $competitionsId)->orderBy('sortorder')->get();
endif;
return $patrols;
}

Вместо этого с этим кодом он работает очень хорошо:

public function getPatrols($competitionsId)
{
if ($this->request->get('patrol_type') == 'finals'):
return PatrolFinals::where('competitions_id', $competitionsId)->orderBy('sortorder')->get();
endif;

if ($this->request->get('patrol_type') == 'distinguish'):
return PatrolDistinguish::where('competitions_id', $competitionsId)->orderBy('sortorder')->get();
endif;
return Patrol::where('competitions_id', $competitionsId)->orderBy('sortorder')->get();
}

Он не проверяет наличие нуля, вместо этого он проверяет другие состояния, и если ни одно из них не является нулевым.

В этом случае тип_патруля равен нулю. Предполагается, что функция получает информацию из базы данных: патрулирование таблиц. Затем он создает сообщения в таблице базы данных: результат. Эти сообщения должны показывать форму, в которую можно вводить результаты. Но ничего не отображается. Это «filter_default.blade.php», который покажет форму для нулевого патруля:


<div class="row">
<div class="col-sm-3">
<div class="panel panel-default">
<div class="panel-heading">{{_('Inmatning')}}</div>
<table class="table table-bordered">
<tbody>
<tr>
<td>{{_('Datum')}}</td>
<td><% competitions.competition.date %></td>
</tr>
<tr>
<td>{{_('Tävlingsgrupp')}}</td>
<td><% (competitions.competition.championship.name)? competitions.competition.championship.name: '-' %></td>
</tr>
<tr ng-if="competitions.competitions.competitiontype">
<td>{{_('Tävlingstyp')}}</td>
<td><% competitions.competitions.competitiontype.name %></td>
</tr>
</tbody>
</table>
<div class="panel-body">
<div class="row form-group">
<div class="col-lg-12">
<label><% competitions.competition.translations.patrols_name_singular | ucfirst %></label>
<select class="form-control" ng-options="patrol.sortorder as (patrol.sortorder+ ' ('+patrol.start_time_human+')') for patrol in results.patrols" ng-model="results.filter.patrol">
<option value=""><% competitions.competition.translations.patrols_name_singular | ucfirst %></option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-lg-6">
<label><% competitions.competition.translations.stations_name_singular | ucfirst %> ({{_('från')}})</label>
<select class="form-control" ng-options="n for n in [] | range:1:competitions.competition.stations_count+1" ng-model="results.filter.station_start">
<option value=""><% competitions.competition.translations.stations_name_singular | ucfirst %></option>
</select>
</div>
<div class="col-lg-6">
<label><% competitions.competition.translations.stations_name_singular | ucfirst %> ({{_('till')}})</label>
<select class="form-control" ng-options="n for n in [] | range:1:competitions.competition.stations_count+1" ng-model="results.filter.station_end">
<option value=""><% competitions.competition.translations.stations_name_singular | ucfirst %></option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-lg-6">
<label><% competitions.competition.translations.patrols_lane_singular | ucfirst %> ({{_('från')}})</label>
<select class="form-control" ng-options="n for n in [] | range:1:competitions.competition.patrol_size+1" ng-model="results.filter.lane_start">
<option value=""><% competitions.competition.translations.patrols_lane_singular | ucfirst %></option>
</select>
</div>
<div class="col-lg-6">
<label><% competitions.competition.translations.patrols_lane_singular | ucfirst %> ({{_('till')}})</label>
<select class="form-control" ng-options="n for n in [] | range:1:competitions.competition.patrol_size+1" ng-model="results.filter.lane_end">
<option value=""><% competitions.competition.translations.patrols_lane_singular | ucfirst %></option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-lg-12">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="results.filter.per_shot" ng-true-value="1" ng-false-value="0"> {{_('Registrera alla skott')}}
</label>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-lg-12">
<div class="checkbox">
<label>
<input type="checkbox" ng-model="results.filter.show_empty_lanes" ng-true-value="1" ng-false-value="0"> {{_('Visa tomma %s')}}
</label>
</div>
</div>
</div>
<a class="btn btn-primary" ui-sref-opts="{reload: true}" ui-sref="competitions.admin.results.registration({competitions_id: competitions.competition.id, patrol:results.filter.patrol, patrol_type:results.filter.patrol_type, station_start: results.filter.station_start, station_end: results.filter.station_end, lane_start:results.filter.lane_start, lane_end:results.filter.lane_end, show_empty_lanes:results.filter.show_empty_lanes, per_shot:results.filter.per_shot})">{{_('Visa')}}</a>
</div>
</div>
</div>
<div class="col-sm-9">
<div ng-if="results.signups">
<div ui-view="military" ng-if="competitions.competition.results_type == 'military'"></div>
<div ui-view="field" ng-if="competitions.competition.results_type == 'field' || competitions.competition.results_type == 'pointfield' || competitions.competition.results_type == 'magnum'"></div>
<div ui-view="precision" ng-if="competitions.competition.results_type == 'precision'"></div>
</div>
</div>
</div>

Вот Models/Result.php:


<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Result extends Model
{
use SoftDeletes;
protected $table = 'results';
protected $fillable = [
'stations_id',
'figure_hits',
'hits',
'points',
'station_figure_hits',
];
protected $casts = [
'station_figure_hits' => 'array',
];
public function Signup()
{
return $this->belongsTo(\App\Models\Signup::class, 'signups_id', 'id');
}
}

Вывод из отладчика:

 "patrol" => "1"
"patrol_type" => null
"station_start" => "1"
"station_end" => "2"
"lane_start" => "1"
"lane_end" => "20"
"show_empty_lanes" => "1"
"per_shot" => "1"

Был бы признателен за некоторые идеи. С уважением, Ральф в Швеции


Решение проблемы

Кажется, что любое другое условие соответствует, и вы возвращаете $patrols; Чтобы избежать ошибки, вы можете вернуться так: return $patrols?? null;или инициировать $$патрули в начале вашей функции. Вместо null у вас есть проверка того, что ожидается.

Комментариев нет:

Отправить комментарий

Laravel Datatable addColumn returns ID of one record only

Я пытаюсь использовать Yajra Datatable для интеграции DataTable на свой веб-сайт. Я смог отобразить таблицу, но столкнулся с проблемой. В по...