cyrildewit / eloquent-viewable

Associate views with Eloquent models in Laravel
MIT License
803 stars 104 forks source link

user id instead of cookie #259

Closed mohammad6006 closed 1 year ago

mohammad6006 commented 2 years ago

Description:

Steps To Reproduce:

I use API and because of that unique function doesn't work.

I decided to store user id instead of cookie

I pass user from apicontroller:

            $user = Auth::user();
            views($news)->viewedBy($user)->record();

I create a custom Views Model:

class Views extends \CyrildeWit\EloquentViewable\Views
{
    protected $viewer;    

    public function viewedBy(User $user)
    {
        $this->viewer = $user;
        return $this;
    }
    /**
     * Create a new view instance.
     *
     * @return \CyrildeWit\EloquentViewable\Contracts\View
     */
    protected function createView(): ViewContract
    {
        $viewer = $this->viewer;

        $view = Container::getInstance()->make(ViewContract::class);

        return $view->create([
            'viewable_id' => $this->viewable->getKey(),
            'viewable_type' => $this->viewable->getMorphClass(),
            'visitor' => $viewer->id,
            'collection' => $this->collection,
            'viewed_at' => Carbon::now(),
        ]);
    }

}

The problem is that $viewer->id return null

Expected behavior:

$user or $this->viewer return user info in viewdBy method but return null in createView method

cyrildewit commented 2 years ago

I find it hard to believe that the $viewer property is empty after explicitly setting it in the controller. Can you check if the $user object returns and id at the different stages of the code.

Instead of extending the Views class you can also provide your own Vistor class. See https://github.com/cyrildewit/eloquent-viewable#create-your-own-visitor-class.

Hope this helps.

mohammad6006 commented 2 years ago

@cyrildewit actually there is no difference

I create a Visitor class

namespace App\Services\Views;

use CyrildeWit\EloquentViewable\Visitor as BaseVisitor;

class Visitor extends BaseVisitor
{
    protected $userid;

    public function getuserid($userid)
    {
        $this->userid = $userid;
        return $this;
    }

    public function id(): string
    {
        return $this->userid;
    }
}

and userid return empty

I logged user id after $this->userid = $userid; and it return user id but after return $this; userid return null

mohammad6006 commented 2 years ago

I test my code on web middleware and it works correctly

then I added

    public function isCrawler(): bool
    {
        return false;
    }

to Visitor class and now it works on api middleware

cyrildewit commented 1 year ago

@mohammad6006 were you testing the API endpoint with Postman? This might have caused the views not being saved, because Postman is recognized as a crawler. You can change the agent in Postman I believe.