VimKanzo

ErrorException: Trying to get property of non-object

laravel Icon

ErrorException

Trying to get property of non-object

An unhandled exception occurred on line 55
52
    public static function generate_new_user_api_key(User $user)
53
    {
54
        // dd($user->apiKey->id);
55
        $userKey = $user->apiKey->id;
56
        $key = uniqid();
57
        $secret = bin2hex(random_bytes(16));

Solution

I have a table that stores API keys in my application. A user can regenerate their API key and locally I was doing to generate a new API key, but the initial function I had first of all checks if there is an already existing key, if there is, it would update that key to a new one.

In my case, there was none in the table so it was trying the error. Below was the code. The error is with the $userKey because there was no exsisting record to get the id of it.


I re-wrote the function. See below:

public static function generate_new_user_api_key(User $user)
    {
        $userAPIKey = ApiKey::UpdateOrCreate([
            'clientId' =>  uniqid(),
            'secret' => bin2hex(random_bytes(16)),
            'user_id' => $user->id
            ]);
    }            
Apr 10, 2021 Anyone

0 replies


Install the browser extension

Found this solution helpful? Try our extension for quick solutions to your Laravel errors.

Chrome logo Add to Chrome - It's free