I cannot figure out why global scope isn't loading with the factory during the tests:
class User extends Authenticatable
{
//...
/**
* The "booted" method of the model.
*/
protected static function booted(): void
{
static::addGlobalScope(new PreviousLogin);
}
/**
* Get Audit relationship.
*/
public function previousLogin(): BelongsTo
{
return $this->belongsTo(Audit::class);
}
}
class PreviousLogin implements Scope
{
/**
* {@inheritDoc}
*/
public function apply(Builder $builder, Model $model): void
{
$builder->addSelect([
'previous_login_id' => Audit::select('id')
->whereColumn('user_id', 'users.id')
->where('event', UserLoggedIn::class)
->latest()
->skip(1)
->take(1),
]);
}
}
class DashboardController extends Controller
{
/**
* Render view.
*/
public function __invoke(Request $request): Response
{
$previousLogin = $request->user()->previousLogin;
return Inertia::render('Dashboard/Index', [
'previous_login' => [
'date' => $previousLogin?->created_at->format('d/m/Y H:i:s'),
'ip' => $previousLogin?->ip_address,
'agent' => $previousLogin?->agent,
],
]);
}
}
/**
* @test
*/
public function renders_view_and_displays_previous_login(): void
{
$audit = Audit::factory()->create([
'created_at' => Carbon::now()->subHour(),
]);
$this->actingAs(User::factory()->create())
->get(route('dashboard'))
->assertInertia(fn(AssertableInertia $page) => $page
->has('previous_login', fn(AssertableInertia $page) => $page
->where('date', $audit->created_at->formated('d/m/Y H:i:s'))
->where('ip', $audit->ip_address)
->where('agent', $audit->agent)
->etc()
)
);
}
When debugging I'm getting:
Illuminate\Database\Eloquent\MissingAttributeException: The attribute [previous_login_id] either does not exist or was not retrieved for model [App\User\Models\User].