'Attempt to read property "username" on bool

I am trying to use "Eager loading relationship" in Laravel.

I use one-to-many relationship, I am trying to access the information I want in the .blade.php file with @foreach but with the error Attempt to read property "username" on bool I'm facing

This is my user model User.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    use HasFactory;
    public function nfts()
    {
        return $this->hasMany(Nft::class);
    }

}

This is my Nft model Nft.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Model;

class Nft extends Model
{
    use HasFactory,SoftDeletes;
    use SoftDeletes;
    protected $table = 'nfts';

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

This is my controller NftController

public function getNft(int $id):view
    {
        $nft = Nft::with('user')->find($id);
        return view('nfts.singleNft', ['nft'=>$nft]);
    }

and this is my userinfo.blade.php page

<tbody>
    @foreach($nft->user as $user)
        <tr>
            <td>1.</td>
            <td>Username</td>
            <td><span class="badge bg-primary">{{$user->username}}</span></td>
            .
            .
            .

What is the problem?



Solution 1:[1]

You iterate over a collection of items.
Your nft is a single model, not a collection.

Drop the foreach

<tbody>
        <tr>
            <td>1.</td>
            <td>Username</td>
            <td><span class="badge bg-primary">{{$nft->user->username}}</span></td>
            .
            .
            .

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 Mostafa Bahri