more
more

Reputation: 133

Trying to get property 'id' of non-object

If I try to log into my app with postman, I get an error on the indicated line:

Trying to get property 'id' of non-object

private $client;

public function __construct()
{
    $this->client = Client::find(1);
}

public function login(Request $request)
{
    $this->validate($request, [
        'username' => 'required',
        'password' => 'required'
    ]);

    return $this->issueToken($request, 'password');
}

public function issueToken(Request $request, $grantType, $scope = "")
{
    $params = [
        'grant_type' => $grantType,
        'client_id' => $this->client->id, // this line has error
        'client_secret' => $this->client->secret,           
        'scope' => $scope
    ];

    if($grantType !== 'social'){
        $params['username'] = $request->username ?: $request->email;
    }

    $request->request->add($params);
    $proxy = Request::create('oauth/token', 'POST');
    return Route::dispatch($proxy);
}

Why am I getting this error message?


Note, on newer versions of PHP, this error will show as:

"Attempt to read property "id" on null

Upvotes: 6

Views: 75179

Answers (4)

Sapnesh Naik
Sapnesh Naik

Reputation: 11636

The error is because $this->client is null when find() cannot find the record.

You need to be sure if the record exists or not.

Change:

$this->client = Client::find(1);

To:

$this->client = Client::findOrFail(1);

Documentation:

From Laravel Eloquent docs, this will throw a 404 error if no record with the specified id is found.

Upvotes: 10

saee
saee

Reputation: 463

I had the same problem when I was trying access an id which doesn't exist in my project database. This $user= user::findOrFail($id); solved my problem.

Upvotes: -1

Sohel0415
Sohel0415

Reputation: 9853

In your issueToken() method-

$client = Client::find(1);
if($client!=null){
     $params = [
       'grant_type' => $grantType,
       'client_id' => $client->id,
       'client_secret' => $client->secret,           
       'scope' => $scope
    ];
}else{
    $params = [
       'grant_type' => $grantType,
       'client_id' => null,
       'client_secret' => null,           
       'scope' => $scope
    ];
}

Upvotes: 0

Nimfus
Nimfus

Reputation: 66

Make sure you have record in database table for User model with id = 1. When you're using User::find(1) Laravel tries to get this record from database, if record is absent this will return null

Upvotes: 1

Related Questions