我正在使用Laravel-5.8作为后端开发Web应用程序。我有一个发帖请求,如下所示:
public function storeClientQuote(Request $request)
{
$user = Auth::user();
$userFirstName = Auth::user()->first_name;
$userLastName = Auth::user()->last_name;
$userEmail = Auth::user()->email;
$dashboardowner = Client::join("users","users.client_id","=","clients.client_id")
->select("clients.client_name", "users.id", "users.first_name", "clients.address1", "clients.address2")
->where('users.id', $user->id)
->get();
if(!Auth::user()->hasPermissionTo('Add Quote'))
return response()->json([ "message" => 'User do not have permission'], 401);
$request->validate([
'phone' => 'required|max:14',
// 'business_name' => 'string',
'truck_type' => 'required',
'truck_required' => 'required',
'quote_origin' => 'required',
'quote_destination' => 'required',
'commodity' => 'required',
'loading_date' => 'date|required'
]);
$clientquote = new ClientQuote;
$clientquote->first_name= $userFirstName;
$clientquote->last_name=$userLastName;
$clientquote->email=$userEmail;
$clientquote->phone=$request->get('phone');
$clientquote->business_name= $dashboardowner[0]->client_name;
$clientquote->address= $dashboardowner[0]->address1 . " " . $dashboardowner[0]->address2;
$clientquote->truck_type=$request->get('truck_type');
$clientquote->truck_required=$request->get('truck_required');
$clientquote->quote_origin=$request->get('quote_origin');
$clientquote->quote_destination=$request->get('quote_destination');
$clientquote->commodity=$request->get('commodity');
$loading_date=date_create($request->get('loading_date'));
$format = date_format($loading_date,"Y-m-d H:i:s");
$clientquote->loading_date = $format;
$clientquote->save();
return response()->json([
'message' => 'Quote Successfully Sent!'
], 201);
}
当我尝试调试时,我发现错误始于:
$ userFirstName = Auth :: user()-> first_name;
显示以下消息:
消息:“试图获取非对象的属性'first_name'”,异常:“ ErrorException”
我该如何解决?
答案 0 :(得分:2)
该消息表示Auth :: user()返回null,这通常在没有登录用户的情况下发生。首先尝试检查用户是否使用Auth::check()
登录,然后再尝试访问Auth::user()
的属性
如果该控制器方法仅用于或已登录用户,则可以在调用该控制器方法的路由上设置Auth Middleware。
并且如果只允许登录用户访问整个控制器,请在控制器构造方法中设置Auth Middleware。
这样,您始终可以确保已登录的用户是可访问的,即Auth :: user()将是一个对象
答案 1 :(得分:0)
尝试
$user = auth()->user();
$userFirstName = $user->first_name;