Trying to get property of non-object - Laravel 5.6
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Debugging Eloquent: How to Avoid "Trying to get property of non-object" in Laravel
As senior developers, we frequently encounter frustrating runtime errors that seem obscure but stem from fundamental misunderstandings of how data flows through our applications. One of the most common—and often most confusing—errors in the Laravel ecosystem is "Trying to get property of non-object."
This issue typically arises when you attempt to access a property (like ->id or ->name) on a variable that holds the value null instead of an actual object instance. While it seems simple, understanding why Eloquent returns null when we expect data is the key to writing robust, production-ready code.
This post will dive into the specific context you presented—handling database results in controllers—and provide concrete solutions using Laravel and Eloquent best practices.
Understanding the Error: Null vs. Object
When you execute an Eloquent query (e.g., Survey::where(...)), if no record matches your criteria, the method will return null, not an empty object or an empty array. When your code immediately tries to call a method on that null result—for example, $surveys->id—PHP throws the "Trying to get property of non-object" fatal error.
The confusion often arises because you might think that if the database is empty, the variable will be an empty array, but for methods like first() or get(), the result when nothing is found is strictly null.
Case Study: Analyzing Your Controller Logic
Let's examine the code snippets you provided to pinpoint where this issue most likely occurs.
The StatController Scenario
In your StatController@home method, the potential failure point lies in how you chain operations based on the result of the initial query:
$surveys = Survey::where('user_id', Auth::user()->id)->orderBy('created_at','DESC')->first();
// If $surveys is null (no surveys found for the user), the next line crashes:
$respondent = Invite::where('user_id', Auth::user()->id)->where('survey_id', $surveys->id)->count();
If $surveys is null, attempting to access $surveys->id immediately throws the error. The same issue applies if you try to access properties on subsequent variables that depend on this initial result.
Handling Empty Results Gracefully
The solution is defensive programming: we must check for the existence of the object before attempting to interact with it. This ensures the application remains stable, even when data is missing.
Here is how you can refactor the logic in StatController to safely handle scenarios where no surveys are found:
public function home(Request $request)
{
$user = Auth::user(); // Cache the user object for cleaner code
// Safely retrieve the survey, defaulting to null if none is found
$survey = Survey::where('user_id', $user->id)->orderBy('created_at','DESC')->first();
if (!$survey) {
// Handle the case where no surveys exist for the user immediately
return view('home', ['surveys' => collect(), 'respondent' => 0, 'yet_to_respond' => 0, 'no_response' => 0, 'answers' => []]);
}
// Only proceed with related queries if a survey was found
$respondent = Invite::where('user_id', $user->id)
->where('survey_id', $survey->id)
->count();
$answers = Invite::where('user_id', $user->id)
->where('link_answered', 1)
->where('survey_id', $survey->id)
->count();
// ... continue with other variables
return view('home', compact('survey', 'respondent', 'answers'));
}
Notice how we added an explicit if (!$survey) check. If the survey doesn't exist, we immediately return a sensible view without attempting to query related data, thus avoiding the error entirely. This practice of validating Eloquent results is crucial when working with complex relationships, which is a core concept in building scalable applications on platforms like Laravel.
Best Practices for Safe Data Access
Beyond simple if statements, modern PHP and Laravel offer cleaner ways to handle optional data:
Null Coalescing Operator (
??): Use this when you expect a value might be missing and want to provide a default fallback.// If $survey is null, use an empty object or handle it gracefully $survey = Survey::where('user_id', Auth::user()->id)->first(); $surveyId = $survey ? $survey->id : null; // Explicitly check and set IDCollection Handling: When using
get(), remember that an empty result returns an emptyIlluminate\Database\Eloquent\Collection. While this isn'tnull, you should still check the count ($contacts->count()) or use methods likefirst()if you only expect one result.
By adopting these defensive coding patterns, you move from reactive debugging (fixing errors after they happen) to proactive data handling, ensuring that your application remains reliable and predictable. For deeper dives into Eloquent relationships and query optimization, always refer back to the official documentation at laravelcompany.com.
Conclusion
The "Trying to get property of non-object" error is a signal: your code is attempting an operation on data that doesn't exist. In the context of Laravel controllers dealing with Eloquent models, this almost always means you failed to account for the possibility that a database query returned null. By implementing explicit checks and utilizing modern PHP features like the null coalescing operator, you can build robust backend logic that gracefully handles missing data, leading to cleaner, more maintainable applications.