从Laravel控制器返回json时尝试获取非对象的属性'id'

时间:2018-11-21 01:03:59

标签: javascript php json laravel vue.js

使用vue提交表单时,我试图获取存储到数据库中的最新记录的ID。这是一回事,但我似乎找不到更好的解决方案。

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

  

试图获取非对象的属性“ id”

我通过检查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
}

控制台输出为:

  

错误=错误:请求失败,状态码为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)

1 个答案:

答案 0 :(得分:1)

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

这将获得ID为整数,并允许轻松比较并减少代码。

这意味着您将在我们的if语句中将$companyViewingId->id更改为$companyViewingId,并在json响应中将$id->id更改为$id

希望这会有所帮助

更新

我会使用url()route()助手来为您的获取网址创建网址

如果要使用route(),则可以使用占位符,例如':id'和use:

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