Laravel - 将数据库值与变量进行比较

时间:2017-04-28 19:08:18

标签: php laravel

我有一个基本的约会系统设置,但是每个登录的人都可以看到所有约会,所以我要做的就是让用户只能看到他们的约会。为此,我试图获取登录用户ID,然后显示具有此user_id值的所有约会(约会是联结表)

我知道我的代码可能很糟糕,但感谢任何帮助,谢谢

function index()
    {
        $logged_user_id = Auth::user()->id;
        $user = User::find($logged_user_id);

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

        return view ('appointment/userappointments',['appointments' => $appointments]);
//      $appointments = Appointment::all();
    } 

2 个答案:

答案 0 :(得分:3)

设置模型关系,你可以这样做

function index()
{
    $appointments = Auth::user()->appointments;
    return view ('appointment/userappointments',['appointments' => $appointments]);
} 

答案 1 :(得分:0)

您已拥有用户ID,无需提取用户信息。

function index()
{
    $logged_user_id = Auth::user()->id;
    $appointments = Appointment::where('user_id', '=' $logged_user_id)->get();

    return view ('appointment/userappointments',['appointments' => $appointments]);
    //$appointments = Appointment::all();
}