WTFranklin
WTFranklin

Reputation: 2568

Trying to get property 'id' of non-object when returning json from laravel controller

I am trying to get the id of the latest record I stored to the database when using vue to submit a form. It's kind of a round about thing, but I can't seem to find a better solution.

After the record is stored I'm querying the database for this record. I get the id of the record from the database no problem when I go directly to route that handles this get request. The issue I have is when I attempt to pass this value back to the vue component, I don't get the id of the record as I expect, instead I get this in the laravel.log file:

Trying to get property 'id' of non-object

I got around this by checking if the value of the id is null and handle that accordingly, but the problem is I still can't get the id of the record which I need for associated a file with the post.

I've tried all the variations I can think of to access the data, such as: $id->id and $id['id']. I tried to turn it in to an associative array by creating a variable to hold the result of json_decode($id->id, true), but either I get the error of property of non-object or the variable is null. I can't seem to figure out what I'm doing wrong. Thank you in advance for any insight or help!

Here is all of the relevant code:

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
}

The console output is:

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)

Upvotes: 0

Views: 1267

Answers (1)

Josh Young
Josh Young

Reputation: 1366

I would change the ->first(['id']) to ->value('id')

This will get the ID as an integer and allow for easy comparison and cut down your code.

This would mean that you you would change $companyViewingId->id to $companyViewingId in our if statement and $id->id to $id in your json response

Hope this helps

Update

I would use the url() or route() helper in creating the url for your get url

If you want to use route() the you can use a place holder such as ':id' and the use:

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

Upvotes: 1

Related Questions