@olliejjc16 why you are doing
$this->actingAs($user)
if just before it you checked that you are authenticated?
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi I'm running tests for a post request to register a user with a teacher role. Registering outside of testing works fine but when I run the test it appears that this line is causing an issue when creating a teacher user
$id = Auth::id();
This gets the id of the logged in user which in this case should be the user id of a logged in SchoolAdmin user. In the app only a logged in user with SchoolAdmin role can create a teacher. The Auth::id gets the logged in id of the SchoolAdmin when the app runs regularly but this causes issues with testing. I tried moving the route to web.php thinking it might be a session issue but didn't solve it
public function test_teachers_registration(){
$this->withoutExceptionHandling();
$user = User::factory()
->has(SchoolAdmin::factory()->count(1), 'schoolAdmin')
->create();
$this->assertGuest();
$response = $this->post('/login', [
'email' => $user->email,
'password' => 'password',
]);
$this->assertAuthenticated();
$response = $this->actingAs($user)->post('/teacher/register', [
'fullName' => 'Test Teacher',
'userName' => 'Test Teacher UserName',
'email' => '[email protected]',
'password' => 'password',
]);
$this->assertDatabaseHas('users', [
'name' => 'Test Teacher',
'username' => 'Test Teacher UserName',
'email' => '[email protected]',
]);
This is my current test case, need to figure out how to have an authenticated SchoolAdmin user in my test so Auth::id will work and the teacher can be registered.
@olliejjc16 It could be either of these
$schoolAdmin->currentTeachers()->save($teacher);
$school->currentTeachers()->save($teacher);
I suspect the latter; where in your test do you set up a School?
Otherwise, your logic is potentially going to result in this same type of error in production; both of these assignments are optimistic that a Model instance will be found:
$schoolAdmin = SchoolAdmin::where('user_id', $id)->first();
// ...
$school = School::where('id', $schoolId)->first();
Coding defensively using firstOrFail would improve matters (IMHO); a relationship between SchoolAdmin and School might be useful either;
$schoolAdmin = SchoolAdmin::where('user_id', $id)->firstOrFail();
$school = School::findOrFail($schoolAdmin->id);
Please or to participate in this conversation.