php - Trying to get property 'uid' of non-object
In blade I'm trying to determine which button needs to show, but I get the following error: Trying to get property 'uid' of non-object.
In my Entry model I made this relation:
public function blockeduser() {
return $this->hasOne(BlockedUser::class);
}
In my BlockedUser model I made this relation:
public function entry() {
return $this->belongsTo(Entry::class);
}
The code in the blade file:
@foreach($entries as $entry)
<tr>
<td style="max-width: 150px;">
<div class="btn-group">
<form target="_blank" method="post" action="{{route('entries.show', $entry->id)}}">
@method("GET")
<button style="margin-right: 5px;" type="submit" class="btn btn-success">View</button>
</form>
@if ($entry->uid !== $entry->blockeduser->uid)
<form method="post" action="{{route('entries.blockUser', $entry->id)}}">
@csrf
<button style="margin-right: 5px;" type="submit" class="btn btn-warning">Block</button>
</form>
@else
<form method="post" action="{{route('entries.unblockUser', $entry->id)}}">
@csrf
<button style="margin-right: 5px;" type="submit" class="btn btn-warning">Unblock</button>
</form>
@endif
<form method="post" action="{{route('entries.destroy', $entry->id)}}">
@csrf
@method("DELETE")
<button style="margin-right: 5px;" type="submit" class="btn btn-danger">Delete</button>
</form>
</div>
</td>
</tr>
@endforeach
How can I access the uid inside the blocked users table that has a relation with the Entry and compare them and determine which form needs te show.
Or is there a way I can check if a table contains a row that has a relation with the Entry?
Possible solution?
Because $entry->blockeduser->uid
was not found I edited the if statement inside the blade file:
@if ($entry->blockeduser == null)
<form method="post" action="{{route('entries.blockUser', $entry->id)}}">
@csrf
<button style="margin-right: 5px;" type="submit" class="btn btn-warning">Block</button>
</form>
@elseif ($entry->blockeduser !== null)
<form method="post" action="{{route('entries.unblockUser', $entry->id)}}">
@csrf
<button style="margin-right: 5px;" type="submit" class="btn btn-warning">Unblock</button>
</form>
@endif
Answer
Solution:
check if $entry->blockeduser
exists before you check the uid
inside that like this:
if ($entry->blockeduser instanceof \App\Models\BlockedUser && $entry->uid !== $entry->blockeduser->uid)
Answer
Solution:
you can use optional global helper if $entry
is null not throw exception
optional($entry)->uid;
Source