Laravel 5.5仅加载当前登录用户的数据

时间:2019-04-07 14:18:19

标签: laravel-5.5

您好,我是laravel的新手,但我想为当前登录的用户加载所有预订。

我尝试这样做

   //check if user is logged in
     if ($user = Auth::user()) {  
       //get only the bookings for the currently logged in user
        $allProducts =Booking::where('client', Auth::user()->name)->where('name', $name)->first();
        //store the bookings in a products variable
        $products = json_decode(json_encode($allProducts));
      //Loop through the products:
        foreach ($products as $key => $val) {
            //get the name of the service by matching it's id in the service model to the service column in the products
            $service_name = Service::where(['id' => $val->service])->first();
      //get the charge amount of the service by matching it's id in the Charge model to the charge column in the products
            $service_fee = Charge::where(['id' => $val->charge])->first();
          //get the status of the service by matching it's id in the status model to the status column in the products
            $service_status = Status::where(['id' => $val->status])->first();
            $products[$key]->service_name = $service_name->name;
            $products[$key]->service_fee = $service_fee->total;
            $products[$key]->service_status = $service_status->name;
        }
        return view('client.booking.view_bookings')->with(compact('products'));
    }
    return view('/login');
}

但这给了我一个错误:未定义的变量:行名

       $allProducts =Booking::where('client', Auth::user()->name)->where('name', $name)->first();

我可能做错了什么?以及如何解决它只能dsplay所需的数据

1 个答案:

答案 0 :(得分:1)

我试图理解您的工作没有成功,但是从您在评论中的解释,我想我知道您想做什么。

由于您说的是这段代码对您而言效果很好,除了它可以为您提供数据库中所有数据的结果,而无论登录用户是什么

    $allProducts = Booking::get();

这是因为它创建了一个查询,该查询选择了数据库中的所有数据。

您需要的是在语句中添加where子句。为此,只需将其添加到上面的代码行中

    where('client', Auth::user()->name)

它将仅返回包含与当前登录用户名称相同的client列的数据。

因此整个代码行变成了

    $allProducts = Booking::get()->where('client', Auth::user()->name);

或者您可以使用过滤器