diff --git a/README.md b/README.md index abc1ee4..f186d58 100644 --- a/README.md +++ b/README.md @@ -31,3 +31,15 @@ In `app/Models/Morningnews.php` file, change it so that the model would work wit Test method `test_create_model_incorrect_table()`. +--- + +## Task 2. Eloquent Get Data. + +In `app/Http/Controllers/UserController.php` file method `index()`, write Eloquent query to get 3 newest users with verified emails, ordered from newest to oldest. Transform this SQL query into Eloquent: + +``` +select * from users where email_verified_at is not null order by created_at desc limit 3 +``` + +Test method `test_users_get()`. + diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php new file mode 100644 index 0000000..66d6333 --- /dev/null +++ b/app/Http/Controllers/UserController.php @@ -0,0 +1,21 @@ + + + + Name + Email + + + + @foreach ($users as $user) + + {{ $loop->iteration }}. {{ $user->name }} + {{ $user->email }} + + @endforeach + + diff --git a/routes/web.php b/routes/web.php index b130397..ed70cc2 100644 --- a/routes/web.php +++ b/routes/web.php @@ -16,3 +16,5 @@ use Illuminate\Support\Facades\Route; Route::get('/', function () { return view('welcome'); }); + +Route::get('users', [\App\Http\Controllers\UserController::class, 'index']); diff --git a/tests/Feature/EloquentTest.php b/tests/Feature/EloquentTest.php index 3cf2f52..4fbfccb 100644 --- a/tests/Feature/EloquentTest.php +++ b/tests/Feature/EloquentTest.php @@ -4,6 +4,7 @@ namespace Tests\Feature; use App\Models\Morningnews; use App\Models\News; +use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; @@ -20,4 +21,27 @@ class EloquentTest extends TestCase $this->assertDatabaseHas('morning_news', $article); } + // TASK: Write Eloquent query to return the newest 3 verified users + public function test_users_get() + { + $user1 = User::factory()->create(['created_at' => now()->subMinutes(5)]); + $user2 = User::factory()->create(['created_at' => now()->subMinutes(4)]); + $user3 = User::factory()->create(['created_at' => now()->subMinutes(3), 'email_verified_at' => NULL]); + $user4 = User::factory()->create(['created_at' => now()->subMinutes(2)]); + $user5 = User::factory()->create(['created_at' => now()->subMinute()]); + + $response = $this->get('users'); + + // This one should be filtered by "email_verified_at is not null" + $response->assertDontSee($user3->name); + + // This one should be filtered out by "limit 3" + $response->assertDontSee($user1->name); + + // Do we have the correct order? + $response->assertSee('1. ' . $user5->name); + $response->assertSee('2. ' . $user4->name); + $response->assertSee('3. ' . $user2->name); // not $user3 + } + }