Trying to get property 'id' of non-object
Encountering the "Trying to get property 'id' of non-object" error in Laravel is a classic symptom of attempting to access an attribute on a model instance that does not exist or has not been loaded. In your specific scenario, the root cause lies in the constructor of your controller class:
public function __construct()
{
$this->client = Client::find(1);
}
This line executes immediately when the application boots up and instantiates your controller. It attempts to fetch a Client model with an ID of 1 from the database. If that record does not exist, $this->client is assigned null. Later, inside the login method, this null value is passed to issueToken, which then tries to access the id property on it.
In PHP 7 and earlier, accessing a property on null throws the "Trying to get property..." error. In PHP 8+, this behavior changed slightly to "Attempt to read property 'id' on null". While the message has evolved, the underlying logic remains identical: you are dereferencing a non-object.
Why the Constructor is the Culprit
The immediate issue with placing $this->client = Client::find(1); in the constructor is that it executes for every single request to that controller, regardless of context. If your database is empty, or if the migration hasn't run yet, this line will fail immediately upon application start-up (if you are using a singleton service provider) or on the very first request.
Even worse, if you have multiple controllers extending this class, every single one tries to load Client::find(1) in their constructor. This not only couples your entire controller hierarchy to a specific database state but also makes debugging difficult because the error happens before any user input is processed.
The Correct Approach: Dependency Injection or Lazy Loading
The most robust solution in Laravel is to avoid hard-coding dependencies in constructors when those dependencies are optional or conditional. Instead, you should inject the dependency or check for its existence before use.
If you require a specific Client instance to function, it is better to ensure that record exists before attempting to access your controller, perhaps via a database seed file or an initialization script. However, if you are building an OAuth flow where the client might not be loaded statically, consider injecting the dependency via a service provider or checking for its existence dynamically.
Here is how you can refactor issueToken to handle the missing client gracefully:
public function issueToken(Request $request, $grantType, $scope = "")
{
// Check if the client exists before trying to access its properties
if (!isset($this->client) || !is_object($this->client)) {
abort(401, 'Client not found.');
}
$params = [
'grant_type' => $grantType,
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'scope' => $scope
];
if($grantType !== 'social'){
$params['username'] = $request->username ?: $request->email;
}
// Ensure the request object is correctly formed before dispatching
// Note: Depending on your specific Laravel version and custom Request logic,
// ensure you are modifying the correct request instance.
$proxy = Request::create('oauth/token', 'POST');
// Pass the original request parameters into the proxy or handle them differently
// as per your specific routing setup
return Route::dispatch($proxy);
}
Ensuring Data Integrity
The error suggests that the Client model with ID 1 is missing. Before deploying your application, verify that your database contains the expected seed data. If you are using migrations and seeds, ensure they have run successfully:
php artisan migrate:fresh --seed
If the record truly should not exist, consider changing your architecture to pass the client_id via the request or query parameters instead of hardcoding it in the constructor. This decouples your controller from a specific database row and makes your application more flexible for different OAuth clients.
Final Considerations
Always assume that database queries can fail due to missing data, especially during development or testing phases where tables might be empty. By moving away from static initialization in constructors for optional resources, you make your code more resilient. If you need further assistance with Laravel dependency injection or OAuth implementation patterns, resources like https://laravelcompany.com offer detailed guides on these specific architectural decisions.
