ChristianKuri / laravel-favorite

Allows Laravel Eloquent models to implement a 'favorite', 'like', 'remember' and 'follow' features.
MIT License
226 stars 48 forks source link

Trying to get property of non-object on $users = $object->favoritedBy() #12

Closed ghost closed 5 years ago

ghost commented 5 years ago

Detailed description

It worked on last version, but since I upgraded Laravel to 5.8 I have this error when I try to get a collection of users that have "favorited" an item.

Context

My Favoriteable model is links (user can favourite any link of the application). My (very simple) Links model:

class Links extends Model
{
    use Favoriteable;
}

My Users model:

class User extends Authenticatable
{
    use Favoriteability;
    [...]
}

In a test controller, I want to

$link = Links::findOrFail(22);
$users = $link->favoritedBy();

Yes link 22 does exist in database :) The error is on $link->favoritedBy(); then on

    public function favoritedBy()
    {
        return $this->favorites()->with('user')->get()->mapWithKeys(function ($item) {
            return [$item['user']->id => $item['user']];
        });
    }

The following are working correctly:

$link = Links::findOrFail($id);
$favoriteCount = $link->favoritesCount;

Will generate select count(*) as aggregate from [favorites] where [favorites].[favoriteable_id] = 22 and [favorites].[favoriteable_id] is not null and [favorites].[favoriteable_type] = 'App\Models\Users\Links' as expected

$link = Links::findOrFail($request->input('link_id'));
$link->toggleFavorite();

Will generate select top 1 1 [exists] from [favorites] where [favorites].[favoriteable_id] = 22 and [favorites].[favoriteable_id] is not null and [favorites].[favoriteable_type] = 'App\Models\Users\Links' and [user_id] = 84 and insert into [favorites] ([user_id], [favoriteable_id], [favoriteable_type], [updated_at], [created_at]) values (84, 22, 'App\Models\Users\Links', '2019-03-19 16:41:19.984', '2019-03-19 16:41:19.984') as expected (same for removing)

Possible implementation

-

Your environment

ghost commented 5 years ago

OK I think I found the problem ; for any reason, we decided to have in our Users table the primary key id_user not id. I fixed the issue by modifying:

Traits\Favoriteable
public function favoritedBy()
{
    return $this->favorites()->with('user')->get()->mapWithKeys(function ($item) {
            return [$item['user']->id_user => $item['user']];
        });
}
Models\Favorite
public function user()
{
        return $this->belongsTo(Config::get('auth.providers.users.model'), 'user_id');
}

So it won't work correctly if we change the default primary key for the Users Model, despite the declaration of protected $primaryKey = 'id_user'; into Users model

ChristianKuri commented 5 years ago

Ok, im glad everything is fixed now, ill check it out and see if I can implement something to take the declared primary key instead of the id directly