问题
i have this on my view im trying to pass $reservations
when there is some reservations in DB there is no error but when it is empty i got error
Undefined variable: reservations (View: C:\Users\yass\Desktop\E-tourisme-44\E-tourisme-5554\resources\views\moderateur\reservation.blade.php)
Template
<tbody>
@if($reservations )
@foreach($reservations as $reservation)
<tr>
<td> {{$reservation->children}} </td>
<td> {{$reservation->checkin}} </td>
<td> {{$reservation->checkout}} </td>
<td>
@endforeach
@else
<div>
No Data
</div>
@endif
</tbody>
and this is my function
public function index()
{
$myhotels = hotel::where('created_by', Auth::user()->id)->first();
if ($myhotels) {
$reservations = Reservation::where('hotel_id', $myhotels->id)->get();
return view('moderateur/reservation', compact('reservations'));
}
return view('moderateur/reservation');
}
回答1:
Try with:
@if(isset($reservations))
回答2:
To make your code work, instead
@if($reservations )
use
@if(! empty($reservations))
Also instead combining @if
with @foreach
for displaying "no data" consider using @forelse @empty
instead. Docs: https://laravel.com/docs/7.x/blade#loops
回答3:
You can use
@isset($reservations)
//your code
@endisset
Or you can write your code like this
{{ $reservations ?? null }}
来源:https://stackoverflow.com/questions/62225494/how-can-i-check-there-is-an-variable-laravel