嗨,我是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();
我能做错什么?以及如何解决它只显示所需的数据
我试图了解你在做什么但没有成功,但是从你在评论中的解释,我想我知道你想做什么。
既然你说这个代码适合你,除了它给你数据库中所有数据的结果,无论登录用户如何
$allProducts = Booking::get();
这是因为它创建了一个选择数据库中所有数据的查询。
您需要的是在语句中添加where子句。要做到这一点,只需将其添加到上面的代码行
where('client', Auth::user()->name)
它将仅返回包含客户端列的数据等于当前登录用户的名称。
因此整个代码行变成了;
$allProducts = Booking::get()->where('client', Auth::user()->name);
或者,您可以使用过滤器