The error message “Attempt to read property ‘id’ on null” in Laravel typically occurs when you’re trying to access the id property of an object that is null. This commonly happens when you’re expecting an object to be returned (such as a database record), but instead, null is returned. You can handle this null value to avoid the error. Here’s how you can troubleshoot and fix it:
Following are few common solutions
Model Not Found
If you are using Eloquent to retrieve a model (e.g., User::find($id) or User::where(’email’, $email)->first()), and it doesn’t find a matching record, it returns null. Accessing the id property on null causes this error.
Solution:
Check if the object is null before accessing its properties.
$user = User::find($id);
if ($user) {
// Access user properties
echo $user->id;
} else {
// Handle the case where no user was found
echo "User not found";
}
Alternatively, You can use firstOrFail(), which will throw a ModelNotFoundException if no model is found. You can catch the exception to handle this type of errors .
try {
$user = User::findOrFail($id);
echo $user->id;
} catch (ModelNotFoundException $e) {
// Handle the exception (e.g., show a 404 page)
return response()->view('errors.404', [], 404);
}
