From 9a522ae509cc2b421f2bb17266d24a3c05497f02 Mon Sep 17 00:00:00 2001 From: PovilasKorop Date: Tue, 16 Nov 2021 08:19:07 +0200 Subject: [PATCH] Task 4 - get or create a record --- README.md | 8 ++++++++ app/Http/Controllers/UserController.php | 9 +++++++++ routes/web.php | 1 + tests/Feature/EloquentTest.php | 14 ++++++++++++++ 4 files changed, 32 insertions(+) diff --git a/README.md b/README.md index 8577550..9e47c30 100644 --- a/README.md +++ b/README.md @@ -51,3 +51,11 @@ In `app/Http/Controllers/UserController.php` file method `show($userId)`, fill i Test method `test_find_user_or_show_404_page()`. +--- + +## Task 4. Get a Single Record or Create a New Record. + +In `app/Http/Controllers/UserController.php` file method `check_create()`, find the user by name and email. If the user is not found, create it (with random password). + +Test method `test_check_or_create_user()`. + diff --git a/app/Http/Controllers/UserController.php b/app/Http/Controllers/UserController.php index 1d16a88..3d31504 100644 --- a/app/Http/Controllers/UserController.php +++ b/app/Http/Controllers/UserController.php @@ -25,4 +25,13 @@ class UserController extends Controller return view('users.show', compact('user')); } + + public function check_create($name, $email) + { + // TASK: find a user by $name and $email + // if not found, create a user with $name, $email and random password + $user = NULL; + + return view('users.show', compact('user')); + } } diff --git a/routes/web.php b/routes/web.php index 287078a..5175dea 100644 --- a/routes/web.php +++ b/routes/web.php @@ -20,3 +20,4 @@ Route::get('/', function () { Route::get('users', [UserController::class, 'index']); Route::get('users/{userId}', [UserController::class, 'show']); +Route::get('users/check/{name}/{email}', [UserController::class, 'check_create']); diff --git a/tests/Feature/EloquentTest.php b/tests/Feature/EloquentTest.php index f9e2c07..fe5b082 100644 --- a/tests/Feature/EloquentTest.php +++ b/tests/Feature/EloquentTest.php @@ -55,4 +55,18 @@ class EloquentTest extends TestCase $response->assertViewHas('user', $user); } + public function test_check_or_create_user() + { + $response = $this->get('users/check/john/john@john.com'); + $response->assertStatus(200); + $this->assertDatabaseHas('users', [ + 'name' => 'john', + 'email' => 'john@john.com' + ]); + + // Same parameters - should NOT create a new user + $this->get('users/check/john/john@john.com'); + $this->assertDatabaseCount('users', 1); + } + }