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
>
<i ></i>
</button>
</form>
@else
<a href="/login">
<button >
<i ></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
CodePudding user response:
In your Post.php Model
public function checkFavourites()
{
if($this->favourite) {
return $this->favourite->count() && auth()->user()->id == $this->favourite->user_id;
}
}
CodePudding user response:
Attempt to read property "user_id" on null because there is no $this->favourite record, its returing null.
in this case $this->favourite === null