Trying to get property 'id' of non-object
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
When working on an application that uses Laravel, you may come across a critical issue where the application crashes with the error: "Trying to get property 'id' of non-object". While this seems like a simple issue, it could be due to various factors. In this blog post, we will explore some common reasons for this error and how to resolve them.
Reason 1: Missing or incorrect object reference
php
private $client;
public function __construct()
{
$this->client = Client::find(1); // this line could be a problem
}
...Reason 2: Incorrect usage of null coalescing operator
In some cases, null coalescing operators can cause this issue if used incorrectly. For instance:php
$var = $this->client?->id ?? 'default_value'; // using null coalescing operator
if(!is_null($this->client)){
$id = $this->client->id;
}else{
$id = 'default_value';
}
public function issueToken(Request $request, $grantType, $scope = '')
{
if(!is_null($this->client)){
$params['client_id'] = $this->client->id;
}else{
$params['client_id'] = 'default_value';
}
...Reason 3: Incorrect method chaining
Sometimes, this error can occur if you're inadvertently chaining methods or accessing properties that do not exist on the current object:php
$client = Client::find(1); // find() method returns a model instance
$params['client_id'] = $this->client->id; // this line still needs to find the client id since there's no direct chain from client to its attributes.
public function issueToken(Request $request, $grantType, $scope = '')
{
if(!is_null($this->client)){
$params['client_id'] = $this->client->id; // this line is correct as it accesses client's id property directly.
...In conclusion, the "Trying to get property 'id' of non-object" error can result from various factors such as incorrect object references, misuse of null coalescing operators, and inappropriate method chaining. By understanding these issues and following best practices while coding, you can effectively resolve these errors and prevent them from occurring in the future.