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












0

















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)









share|improve this question





























    0

















    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)









    share|improve this question



























      0












      0








      0










      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)









      share|improve this question


















      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)






      javascript php json laravel vue.js






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 1:50







      Frank A.

















      asked Nov 21 '18 at 1:03









      Frank A.Frank A.

      7181712




      7181712
























          1 Answer
          1






          active

          oldest

          votes


















          1














          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)';





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403886%2ftrying-to-get-property-id-of-non-object-when-returning-json-from-laravel-contr%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            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)';





            share|improve this answer






























              1














              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)';





              share|improve this answer




























                1












                1








                1







                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)';





                share|improve this answer















                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)';






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 21 '18 at 1:54

























                answered Nov 21 '18 at 1:48









                JoshJosh

                713215




                713215
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53403886%2ftrying-to-get-property-id-of-non-object-when-returning-json-from-laravel-contr%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Xamarin.form Move up view when keyboard appear

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Anylogic : not able to use stopDelay()