how can i check there is an variable laravel?

被刻印的时光 ゝ 提交于 2020-06-16 17:16:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!