# Laravel/PHP 8: ErrorException: Attempt to read property "name" on null

**Code:** `Attempt to read property "x" on null` · **Category:** Laravel · **Seen on:** Laravel, PHP

You accessed a property on a value that is `null`, typically an empty relationship or a query that found nothing.

## Meaning

`$post->user->name` fails if `user` is null (no related row or soft-deleted). Use the null-safe operator `$post->user?->name`, `optional()`, eager-load with default models (`withDefault()`), or check existence. In Blade use `{{ $post->user?->name }}`.

## Common causes

- Relationship returns null (no related row)
- `first()` found no record
- Soft-deleted parent
- Eager loading missing key
- Wrong foreign key in relation

## Quick fix

1. Use `$post->user?->name` or `optional($post->user)->name`
2. Add `->withDefault()` in the `belongsTo` relation
3. Validate that the record exists (`firstOrFail`)

## Detailed fix by platform

### Laravel

1. `public function user() { return $this->belongsTo(User::class)->withDefault(['name' => 'Guest']); }`

## How to diagnose

1. **Value** — Null where?
2. **Relation** — Row exists?
3. **Guard** — ?-> used?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/laravel/attempt-to-read-property-on-null)
