'Laravel 8 make 2 relationship between the same model

So, this is my relationship method on file model:

public function User()
{
    return $this->belongsTo(
        User::class,
        'user_id',
        'id'
    );
}

public function modify()
{
    return $this->belongsTo(
        User::class,
        'update_id',
        'id'
    );
}

This is my model table

This is my model migration code

public function up()
{
    Schema::create('files', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained()->cascadeOnUpdate()->cascadeOnDelete();
        $table->foreignId('update_id')->nullable()->references('id')->on('users');
        $table->foreignId('division_id')->constrained()->cascadeOnUpdate();
        $table->string('title');
        $table->string('slug')->unique();
        $table->text('details');
        $table->timestamp('published_at')->nullable();
        $table->timestamps();
    });
}

This is my view code:

@foreach ($files as $key=>$file)    
          <tr>
            <td>{{ $files->firstItem() + $key }}</td>
            <td>{{ $file->title }}</td>
            <td><a href="{{ route('Files.index', ['division'=>$file->division->slug, 'byUser'=>$byUser]) }}">{{ $file->division->name }}</a></td>
            <td>
                @if (auth()->user()->id == 1)
                    <a href="{{ route('Files.index', ['division'=>$division, 'byUser'=>$file->user->username]) }}">{{ $file->user->name }}</a>
                @else
                    {{ $file->user->name }}
                @endif
            </td>
            <td>{{ $file->created_at }}</td>
            <td>
                {{-- @foreach ($file->modify as $update) --}}
                    {{ dd($file->modify->name) }}

This is my page view look like after executing code above

after change this line:

{{ dd($file->modify->name) }}

to:

{{ ($file->modify->name) }}

i got the following error:

ErrorException Trying to get property 'name' of non-object



Solution 1:[1]

It would seem like the first $file in you array has the modify relationship set but there's a subsequent $file that's missing it. Either do a null check or make sure that the relationship is always set.

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 Ray Dabbah