i create favourites,but i have a problem. favourites migration
$table->integer('user_id');
$table->integer('favouriteable_id');
$table->string('favouriteable_type');
Favourite.php
protected $fillable = ['user_id'];
public function favouriteable()
{
return $this->morphTo();
}
Post.php
public function favourite()
{
return $this->morphOne(Favourite::class, 'favouriteable');
}
public function checkFavourites()
{
return $this->favourite->count() && auth()->user()->id == $this->favourite->user_id;
}
view file
@auth
<form action="{{route('add-favorites', $data->id)}}" method="post">
@csrf
<button
class="project like_Heart Button_Search lp-glass lp-rounded-min lp-cu text-bold ho">
<i class="fa-duotone fa-circle-heart lp-lg favorite @if($data->checkFavourites()) active @endif"></i>
</button>
</form>
@else
<a href="/login">
<button class="project like_Heart Button_Search lp-glass lp-rounded-min lp-cu text-bold ho">
<i class="fa-duotone fa-circle-heart lp-lg favorite"></i>
</button>
</a>
@endif
it,s work but problem this here.If a post is added to the favorites by the user, there is no problem and it works, otherwise I get this error
Attempt to read property "user_id" on null
Attempt to read property "user_id" on null because there is no $this-> favorite record. It's returning null, in this case.
$this->favourite === null