'I get this error: Attempt to read property "Username" on null, when trying to display the username [duplicate]

I am trying to display the Username on the web page, but I keep on getting the error

Here is my blade template

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-8">
            <img src="/storage/{{$post->image}}" class="w-100">
        </div>
    </div>
        <div class="col-4">
            <div>
                <h3>{{ $post->user->Username}}</h3>

                <p>{{ $post->caption }}</p>
            </div>

        </div>
</div>
@endsection

Posts controller

    public function show(\App\Models\Post $post)
    {
     
        return view('posts.show', compact ('post'));
    }

    
}

Here are my web Routes


Route::get('/p/{post}', [App\Http\Controllers\PostsController::class, 'show']);

Route::get('/p/create', [App\Http\Controllers\PostsController::class, 'create'])->name('posts.create');

Route::post('/p', [App\Http\Controllers\PostsController::class, 'store']);

Route::get('/Profile/{user}', [App\Http\Controllers\ProfilesController::class, 'index'])->name('Profile.show');



Solution 1:[1]

So you trying to get "Username" property from user model relation.

You need to define your relation on the model : Post Model

...
//Add this so it's gonna retrieve the User model
public $with = ['user']

function user(){
  return $this->belongsTo(User::class);
}
...

Or you can add with('user') in the controller

$data = Post::with('user')->first()

Hope it help!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arif Nurdiansyah