'how to create favourite system in laravel with relations with multi model

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


Solution 1:[1]

In your Post.php Model

public function checkFavourites()
    {
        if($this->favourite) {
            return $this->favourite->count() && auth()->user()->id == $this->favourite->user_id;
        }
    }

Solution 2:[2]

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

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 Anuj Kumar
Solution 2 Karl Hill