ImArtur
116
3
Laravel

Laravel bug in traits boot method auth access?

Posted 1 year ago by ImArtur

I have some weird problem. I'm following TDD tutorial, and right now i'm trying to test something this way:

public function test_it_records_activity_when_a_thread_is_created()
    {
        $this->signIn();

        $thread = create(Thread::class, ['user_id' => auth()->id()]);

        $this->assertDatabaseHas('activities', [
            'type' => 'created_thread',
            'user_id' => auth()->id(),
            'subject_id' => $thread->id,
            'subject_type' => 'App\Thread',
        ]);

        $activity = Activity::first();

        $this->assertEquals($activity->subject->id, $thread->id);
    }

Everything is kind of ok, I noticed that

auth()->user()

Is null in traits boot Method but in other trait methods it is working fine.

Trait:


trait RecordActivityTrait
{

    protected static function bootRecordActivityTrait()
    {
        dd(auth()->id()); <----- This returns null even if im logged in
        static::created(function ($model) {
            $model->recordActivity('created');
        });

    }

I noticed someone with the same issue an me: https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/25

``having trouble with

if (auth()->guest()) return;

in the boot method of the trait. the auth check just returns null no matter what. i've confirmed I'm booting the trait in the model

I've also confirmed my middleware look the same as Jeff's.

Any tips?``

Any ideas?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.