Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

Logging in User Types

I have a single sign-in route that is reachable by any of three user types. A teacher, student, admin. I have a User model, Student, and Teacher models with users, teachers, and students tables. Both the teacher's table and students table has a user_id. We are also using the Spatie role and permissions package. What I’m wanting to do is fix my actAs() method so that it can log in a new model based on the state I pass in. Suggestions on what I should do so that I can make sure I'm logging in a student or a teacher or admin.

/**
     * Creates a user with a given state and logs them into the system.
     *
     * @param  array  $states
     * @param  array  $attributes
     * @return \App\Models\User  $user
     */
    public function actAs($states = [], $attributes = [])
    {
        $user = ($states instanceof User) ? $states : factory(User::class)->states($states)->create($attributes);
        $this->actingAs($user);

        return $user;
    }
0 likes
2 replies
OriOn's avatar

I think you should return $this and not $user

For the rest you need to make sure the permission is created according to spatie instructions for testing (on their readme) Not sure if you can do that in your UserFactory->state()

Same goes for the role if you use them

OriOn's avatar

I meant not sure you can do that in the factory.

What I usually do is create all my type of users in the set up and then log in different one for different tests

Also since you are using this package, why create tables for different types of users? In the end aren't Student and Professor just roles for a single user model?

Please or to participate in this conversation.