Skip to content

Commit c27924c

Browse files
Add tests for the mutator
1 parent 55e80a2 commit c27924c

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

tests/ModelTest.php

+18
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
77
use Illuminate\Database\Eloquent\ModelNotFoundException;
88
use Illuminate\Support\Facades\Date;
9+
use Illuminate\Support\Str;
910
use Jenssegers\Mongodb\Collection;
1011
use Jenssegers\Mongodb\Connection;
1112
use Jenssegers\Mongodb\Eloquent\Model;
@@ -678,6 +679,23 @@ public function testDotNotation(): void
678679
$this->assertEquals('Strasbourg', $user['address.city']);
679680
}
680681

682+
public function testAttributeMutator(): void
683+
{
684+
$username = 'JaneDoe';
685+
$usernameSlug = Str::slug($username);
686+
$user = User::create([
687+
'name' => 'Jane Doe',
688+
'username' => $username,
689+
]);
690+
691+
$this->assertNotEquals($username, $user->getAttribute('username'));
692+
$this->assertNotEquals($username, $user['username']);
693+
$this->assertNotEquals($username, $user->username);
694+
$this->assertEquals($usernameSlug, $user->getAttribute('username'));
695+
$this->assertEquals($usernameSlug, $user['username']);
696+
$this->assertEquals($usernameSlug, $user->username);
697+
}
698+
681699
public function testMultipleLevelDotNotation(): void
682700
{
683701
/** @var Book $book */

tests/models/User.php

+15-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@
66
use Illuminate\Auth\Passwords\CanResetPassword;
77
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
88
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
9+
use Illuminate\Database\Eloquent\Casts\Attribute;
910
use Illuminate\Notifications\Notifiable;
11+
use Illuminate\Support\Str;
1012
use Jenssegers\Mongodb\Eloquent\HybridRelations;
1113
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
1214

@@ -21,10 +23,14 @@
2123
* @property \Carbon\Carbon $birthday
2224
* @property \Carbon\Carbon $created_at
2325
* @property \Carbon\Carbon $updated_at
26+
* @property string $username
2427
*/
2528
class User extends Eloquent implements AuthenticatableContract, CanResetPasswordContract
2629
{
27-
use Authenticatable, CanResetPassword, HybridRelations, Notifiable;
30+
use Authenticatable;
31+
use CanResetPassword;
32+
use HybridRelations;
33+
use Notifiable;
2834

2935
protected $connection = 'mongodb';
3036
protected $dates = ['birthday', 'entry.date'];
@@ -84,4 +90,12 @@ protected function serializeDate(DateTimeInterface $date)
8490
{
8591
return $date->format('l jS \of F Y h:i:s A');
8692
}
93+
94+
protected function username(): Attribute
95+
{
96+
return Attribute::make(
97+
get: fn ($value) => $value,
98+
set: fn ($value) => Str::slug($value)
99+
);
100+
}
87101
}

0 commit comments

Comments
 (0)