foreach 循环中的 if 语句

If statement within a foreach loop

我正在尝试创建一个基本的约会系统。当用户登录时,if 语句应该显示他们的个人约会,但目前显示的是每个人的约会。

if 语句的目的是检查他们的用户 ID 以查看是否有任何约会使用此用户 ID 并显示这些约会

我的appointmentstable有一个user_id,而我的userstable只有一个普通的id

@section('content')
    <h1>Your Appointments</h1>
    @foreach ($appointments as $appointment)
        @if ($appointment->user->id == $appointment->user_id)
            <p>
                <a href="{{url('details/'.$appointment->id)}}" >{{$appointment->doctor->name}} : {{$appointment->time}} : {{$appointment->date}}</a>        
            </p>
        @endif
    @endforeach
@endsection

它将始终显示每个人的约会,因为您正在比较 appointment 关联的 user->id 和相同的 appointment->user_id

我认为您应该更改 if 语句并将其与登录用户会话 ID 进行比较,如下所示:

$logged_user_id = Auth::user()->id;

@if ($logged_user_id == $appointment->user_id)

我们可以通过选择与经过身份验证的用户相关的约会来减少视图中的逻辑,而不是使用此嵌套的 if 语句,因此在您的控制器中我们将执行所有约会而不是传递所有约会:

$appointments = Appointment::where('user_id', Auth::user()->id);

因此在您看来,您可以仅使用 foreach($appointments as $appointment) 来遍历它们,而无需检查约会是否与当前用户相关。