Trying to get property of non-object: Diagnosing Lazy Loading in Laravel 5
Encountering the ErrorException: Trying to get property of non-object is a frequent stumbling block when building relationships in Laravel. In your specific case, you are attempting to access $article->postedBy->name, but the $article model instance does not have an associated User object loaded into memory. While your relationship definition ($this->belongsTo('App\User')) and database schema appear correct, Laravel adheres to a strict separation between defining relationships and actually fetching them.
Laravel models are designed to be lightweight by default. When you retrieve a record using News::where('slug', $slug)->firstOrFail(), the query only selects the columns explicitly requested or those defined in $fillable (or just all columns if no scope is applied). Crucially, this initial query does not include data for related models unless you explicitly tell it to. Consequently, when your Blade template tries to evaluate $article->postedBy, Laravel attempts to access a foreign key relationship on an object where that specific association hasn't been resolved yet.
The Missing Eager Load
The root cause is that the News model instance exists without its associated User. In Laravel, relationships are lazily loaded by default. Accessing $article->postedBy triggers a query to fetch the user only if it hasn't been fetched already. However, if the relationship does not exist for that specific record (i.e., the user_id column is NULL in the news table), or if you are accessing a property on the relationship instance before it is resolved, you might hit this error.
More commonly, the error "Trying to get property of non-object" when accessing $article->postedBy->name implies that $article->postedBy itself evaluates to null. This happens in two main scenarios:
- The
user_idforeign key column in yournewstable is NULL for that specific record. - You are trying to access a property on a relationship instance that hasn't been loaded, and the underlying data doesn't exist.
To resolve this, you must ensure the relationship is eager loaded before accessing it in your view. Modify your controller's showArticle method to include the with() clause:
public function showArticle($slug)
{
$article = News::where('slug', $slug)
->with(['postedBy'])
->firstOrFail();
return view('article', compact('article'));
}
By adding ->with(['postedBy']), Laravel generates a single SQL query that joins the news and users tables. It retrieves both the news content and the user details in one go. This prevents the extra query overhead (the N+1 problem) and ensures that $article->postedBy returns a fully populated User model instance rather than null.
Handling Null Relationships Gracefully
Even with eager loading, if your database allows posts without an author (where user_id is NULL), accessing $article->postedBy will still return a User model with null attributes. Attempting to access $article->postedBy->name on such a record would technically work in some contexts but might result in an empty string or unexpected behavior depending on the specific version of Laravel and how the relationship is cast.
However, the specific error "Trying to get property of non-object" usually means the User model instance itself is null. This strongly suggests that for the $article record you are viewing, there is no corresponding row in the users table linked via the foreign key.
If you expect every news item to have an author but one is missing, you should handle the null case explicitly in your Blade template to prevent crashes:
@php
$authorName = $article->postedBy ? $article->postedBy->name : 'Unknown Author';
@endphp
{{ $authorName }}
Alternatively, you can use the ?? operator if you are confident the relationship object exists but properties might be missing:
{{ $article->postedBy?->name ?? 'Guest' }}
Conclusion
The error stems from accessing a relationship that hasn't been loaded or doesn't exist in the database row. By using with() in your controller to eager load the relationship and adding null checks in your view, you ensure a robust user experience regardless of data inconsistencies. For more details on managing relationships effectively, resources like LaravelCompany offer guides on advanced querying patterns, though understanding the core lazy-loading mechanism is essential for debugging these issues quickly.
