gpt4 book ai didi

javascript - 从 laravel Controller 返回 json 时尝试获取非对象的属性 'id'

转载 作者:行者123 更新时间:2023-12-03 00:42:10 24 4
gpt4 key购买 nike

我试图获取使用vue提交表单时存储到数据库的最新记录的id。这有点绕,但我似乎找不到更好的解决方案。

存储记录后,我正在数据库中查询该记录。我得到id当我直接转到处理此获取请求的路由时,数据库中的记录没有问题。我遇到的问题是,当我尝试将此值传递回 vue 组件时,我没有得到 id正如我所期望的那样,我在 laravel.log 中得到了这个记录文件:

Trying to get property 'id' of non-object

我通过检查 id 的值是否解决了这个问题是 null并相应地处理它,但问题是我仍然无法获取将文件与帖子关联起来所需的记录 ID。

我已经尝试了所有我能想到的访问数据的变体,例如:$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 = Error: Request failed with status code 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)

最佳答案

我会将 ->first(['id']) 更改为 ->value('id')

这将获取整数形式的 ID,并可以轻松比较并减少代码。

这意味着您需要在 if 语句和 $id->id 中将 $companyViewingId->id 更改为 $companyViewingId到 json 响应中的 $id

希望这有帮助

更新

我将使用 url()route() 帮助器为您的 get url 创建 url

如果您想使用route(),您可以使用占位符,例如“:id”并使用:

url = url.replace(':id', company)';

关于javascript - 从 laravel Controller 返回 json 时尝试获取非对象的属性 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53403886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com