Skip to content

Instantly share code, notes, and snippets.

@shahmal1yev
Created September 15, 2025 00:41
Show Gist options
  • Save shahmal1yev/d1b23c40ef3e8af7f1a454b38271e1ac to your computer and use it in GitHub Desktop.
Save shahmal1yev/d1b23c40ef3e8af7f1a454b38271e1ac to your computer and use it in GitHub Desktop.
Laravel API Testing Traits
<?php
trait WithAuth
{
use WithUser;
public function getJson($uri, array $headers = [], $options = 0)
{
$this->actingAs();
return parent::getJson($uri, $headers, $options);
}
public function postJson($uri, array $data = [], array $headers = [], $options = 0)
{
$this->actingAs();
return parent::postJson($uri, $data, $headers, $options);
}
public function putJson($uri, array $data = [], array $headers = [], $options = 0)
{
$this->actingAs();
return parent::putJson($uri, $data, $headers, $options);
}
public function patchJson($uri, array $data = [], array $headers = [], $options = 0)
{
$this->actingAs();
return parent::patchJson($uri, $data, $headers, $options);
}
public function deleteJson($uri, array $data = [], array $headers = [], $options = 0)
{
$this->actingAs();
return parent::deleteJson($uri, $data, $headers, $options);
}
}
<?php
trait WithUser
{
protected ?User $user = null;
protected Role|RoleModel|null $role = Role::ADMIN;
protected function resolveUser(): ?User
{
if ($this->role === null) {
return null;
}
if ($this->user === null) {
if ($this->role instanceof Role) {
$this->role = RoleModel::query()->firstOrCreate([
'name' => $this->role,
'guard_name' => 'api',
]);
}
$this->user = User::factory()->create()->assignRole($this->role);
}
return $this->user;
}
public function actingAs(?UserContract $user = null, $guard = null): static
{
if ($resolvedUser = $this->resolveUser()) {
return parent::actingAs($user ?? $resolvedUser, $guard ?? 'api');
}
return $this;
}
protected function withRole(?Role $role): self
{
$this->role = $role;
$this->user = null;
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment