У меня есть UserController, у которого есть метод index () для получения прошлой и следующей регистрации пользователя auth в конференциях.
Затем в представлении я показываю на вкладке следующие регистрации, а на другой вкладке - прошедшие регистрации.
На db есть только одна конференция с end_date "2018-06-15 15:30:00". И у пользователя есть только одна регистрация на этой конференции.
Таким образом, с датой «2018-06-15 15:30:00» это следующая регистрация, но во вкладке прошлых регистраций также появляется регистрация пользователя в конференции с датой «2018-06-15 15: 30:00 ». Но он должен появиться только на следующей вкладке регистрации, поскольку это следующая регистрация.
Вы знаете, почему foreach "@foreach($pastRegistrations as $pastRegistration)" также возвращает результат?
Итак, у меня есть раздел, чтобы показать прошлые регистрации:
@foreach($pastRegistrations as $pastRegistration)
@if (!empty($pastRegistration->conference || !empty($pastRegistration->conference->start_date)))
<li class = "list-group-item">
<h5>{{optional($pastRegistration->conference)->name}}</h5>
</li>
@endif
@endforeach
<div class = "text-center d-flex justify-content-center mt-3">
{{$pastRegistrations->fragment('pastConferences')->links("pagination::bootstrap-4")}}
</div>
И чтобы показать следующие регистрации:
@foreach($nextRegistrations as $nextRegistration)
@if (!empty($nextRegistration->conference || !empty($nextRegistration->conference->start_date)))
<li class = "list-group-item">
<h5>{{optional($nextRegistration->conference)->name}}</h5>
@if ($nextRegistration->status === 'I')
<a href = "{{route('conferences.payment',
['id' => $nextRegistration->conference->id,
'regID'=> $nextRegistration->id])}}"
class = "btn btn-primary ml-2">Pay
</a>
@endif
</li>
@endif
@endforeach
<div class = "text-center d-flex justify-content-center mt-3">
{{$nextRegistrations->fragment('nextConferences')->links("pagination::bootstrap-4")}}
</div>
UserController index (), который возвращает прошлые и следующие регистрации:
class UserController extends Controller
{
public function index(Request $request){
$pageLimit = 5;
$user = $request->user();
$pastRegistrations = $user->registrations()->with(['conference' => function ($query) {
$query->where('end_date', '<', now());
}])->paginate($pageLimit);
$nextRegistrations = $user->registrations()->with(['conference' => function ($query) {
$query->where('end_date', '>', now());
}])->paginate($pageLimit);
return view('users.index',
compact('user', 'pastRegistrations','nextRegistrations'));
}
"Dd ($ pastRegistrations);" показывает:
LengthAwarePaginator {#276 ▼
#total: 1
#lastPage: 1
#items: Collection {#272 ▼
#items: array:1 [▼
0 => Registration {#270 ▼
#fillable: array:3 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [▼
"id" => 1
"status" => "C"
"conference_id" => 1
"main_participant_id" => 1
"created_at" => "2018-06-14 00:09:39"
"updated_at" => "2018-06-14 00:09:39"
]
#original: array:6 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"conference" => null
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
#perPage: 5
#currentPage: 1
#path: "http://proj.test/user/profile"
#query: []
#fragment: null
#pageName: "page"
}
"Dd ($ nextRegistrations);" показывает:
LengthAwarePaginator {#279 ▼
#total: 1
#lastPage: 1
#items: Collection {#274 ▼
#items: array:1 [▼
0 => Registration {#280 ▼
#fillable: array:3 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:6 [▼
"id" => 1
"status" => "C"
"conference_id" => 1
"main_participant_id" => 1
"created_at" => "2018-06-14 00:09:39"
"updated_at" => "2018-06-14 00:09:39"
]
#original: array:6 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"conference" => Conference {#281 ▼
#fillable: array:18 [▶]
#dates: array:2 [▶]
#appends: array:1 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:23 [▶]
#original: array:23 [▶]
#changes: []
#casts: []
#dateFormat: null
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
]
}
#perPage: 5
#currentPage: 1
#path: "http://proj.test/user/profile"
#query: []
#fragment: null
#pageName: "page"
}






Может быть проблема в опечатке @ строка 2:
@if (!empty($pastRegistration->conference || !empty($pastRegistration->conference->start_date)))
вместо
@if (!empty($pastRegistration->conference) || !empty($pastRegistration->conference->start_date))
Взгляните на метод где. Это позволяет вам ограничивать результаты на основе ограничений связанных моделей.
Попробуй это:
$pastRegistrations = $user->registrations()->whereHas('conference', function ($query) {
$query->where('end_date', '<', now());
})->paginate($pageLimit);
$nextRegistrations = $user->registrations()->whereHas('conference', function ($query) {
$query->where('end_date', '>', now());
})->paginate($pageLimit);
Спасибо, но такая же проблема. Но так, $ pstRegistrations показывает пустую коллекцию "LengthAwarePaginator {# 271 ▼ #total: 0 #lastPage: 1 #items: Collection {# 272 ▼ #items: []} #perPage: 5 #currentPage: 1 #path:" proj.test / пользователь / профиль "#query: [] #fragment: null #pageName:" page "}".
Но $ nextRegistrations не пусто: LengthAwarePaginator {# 277 ▼ #total: 1 #lastPage: 1 #items: Collection {# 276 ▼ #items: array: 1 [▼ 0 => Registration {# 280 ▶}]} #perPage: 5 #currentPage: 1 #path: "proj.test / пользователь / профиль" #query: [] #fragment: null #pageName: "page"}.
Возможно, проблема заключается в том, чтобы показать результаты.
Разве $pstRegistrations не должна быть пустой коллекцией? В будущем будет только одна регистрация.
Да, вроде правильно, но проблема та же. Но похоже, что невозможно получить детали конференции, например, название.
Джон, сравнивать даты всегда немного больно, и я предполагаю, что запрос не дает вам правильной информации. К счастью, у Laravel есть встроенное решение в Eloquent, чтобы немного облегчить жизнь: whereDate () Документы (примерно на 2/3 страницы ниже)
Попробуйте изменить свои запросы на функцию Laravel whereDate:
$pastRegistrations = $user->registrations()->whereHas('conference', function ($query) {
$query->whereDate('end_date', '<', now());
})->paginate($pageLimit);
Также, возможно, стоит изучить встроенные функции \ Carbon, так как они также могут значительно облегчить жизнь. Если вы их используете, просто замените now() на \Carbon\Carbon::now().
Поиграйте с методом whereDate в простом запросе, чтобы увидеть, действительно ли здесь проблема.
Спасибо, похоже, что "strpos () ожидает, что параметр 1 будет строкой, заданным массивом".
Извините - опечатка в строке whereHas. Вы можете попробовать это как есть ... или, может быть, просто поиграться с более простым запросом, используя whereDate. Так или иначе, я исправил опечатку - теперь все должно работать.
Спасибо, но такая же проблема.