【发布时间】:2019-04-23 12:57:06
【问题描述】:
我正在尝试获取我在使用 vue 提交表单时存储到数据库中的最新记录的 id。这是一个回合的事情,但我似乎无法找到更好的解决方案。
记录存储后,我正在数据库中查询该记录。当我直接转到处理此获取请求的路由时,我从数据库中获取记录的id 没有问题。我遇到的问题是,当我尝试将此值传递回 vue 组件时,我没有得到预期的记录的id,而是在laravel.log 文件中得到它:
试图获取非对象的属性“id”
我通过检查id 的值是否为null 并相应地处理它来解决这个问题,但问题是我仍然无法获得将文件与邮政。
我已经尝试了所有我能想到的访问数据的变体,例如:$id->id 和 $id['id']。我试图通过创建一个变量来保存json_decode($id->id, true) 的结果,将其转换为关联数组,但要么我得到非对象属性的错误,要么变量为null。我似乎无法弄清楚我做错了什么。提前感谢您的任何见解或帮助!
以下是所有相关代码:
ActionLogComponent.vue
getLatestAction(company) {
let url = '/latest-action/' + company;
let id = 'error';
axios.get(url)
.then(response => {
console.log(response);
// id = response.data.id;
})
.catch(error => {
console.log("error = " + error);
});
return id;
},
ActionLogController.php
public function getLatestAction($company)
{
// $userName = Auth::user()->name;
$userCompanyId = Auth::user()->company_id;
$userCompany = Company::where('id', '=', $userCompanyId)->first(['name']);
$companyViewingId = Company::where('name', '=' , $company)->first(['id']);
if($userCompanyId == $companyViewingId->id)
{
$id = ActionLog::where('activity_key', '=', "1," . $companyViewingId->id)
->orderBy('created_at', 'desc')
->first(['id']);
// outputs id as expected when going directly to the route
// dd($id->id);
// returns hard coded integer as expected
// return 3;
if(!is_null($id))
return response()->json(['id' => $id->id], 200); //This is line 557
// outputs json when going directly to the route and errors in component
else
return response()->json(['error' => 'No record found.'], 404);
// This gets returned every time
}
// user is attempting to view something they don't have permission to see
return response()->json(['error' => -1], 403);
// this only gets returned if the user is not logged in or they are
// attempting to force a different company name in the url
}
控制台输出为:
error = 错误:请求失败,状态码为 404
laravel.log
[2018-11-21 00:02:31] development.ERROR: Trying to get property 'id' of non-object {"userId":1,"email":"frank@******.com","exception":"[object] (ErrorException(code: 0): Trying to get property 'id' of non-object at /Users/frankaddelia/Sites/ast_portal/app/Http/Controllers/ActionLogController.php:557)
【问题讨论】:
标签: javascript php json laravel vue.js