1+ <?php
2+
3+ use Core \App ;
4+ use Core \Database ;
5+ use Core \Validator ;
6+
7+ // $config = require base_path('config.php');
8+ // $db = new Database($config['database']);
9+ $ db = App::resolve (Database::class);
10+
11+ $ currentUserId = 1 ;
12+
13+ //find the corresponding note
14+ $ note = $ db ->query ('select * from notes where id = :id ' , [
15+ 'id ' => $ _POST ['id ' ]
16+ ])->findOrFail ();
17+
18+ // authorize the current user can update/edit the note
19+ authorize ($ note ['user_id ' ] === $ currentUserId );
20+
21+ // validate the form like if you don't include anything or you include too much characters
22+ $ errors = [];
23+
24+ if (! Validator::string ($ _POST ['body ' ], 1 , 1000 )) {
25+ $ errors ['body ' ] = 'A body of no more than 1,000 characters is required. ' ;
26+ }
27+
28+
29+ // if no validation errors, update the record in the notes database table.
30+
31+ // if if we do have validation errors, we return the view with the errors
32+ // but again later we will learn about a process where if the validation fails,
33+ // you redirect to the specific controller (ex sessions and flash messages etc.)
34+ // for now we return the view directly with the errors
35+ if (count ($ errors )){
36+ return view ('notes/edit.view.php ' , [
37+ 'heading ' => 'Edit Note ' ,
38+ 'errors ' => $ errors ,
39+ 'note ' => $ note
40+ ]);
41+ }
42+
43+ $ db ->query ('UPDATE notes SET body = :body where id = :id ' , [
44+ 'id ' => $ _POST ['id ' ],
45+ 'body ' => $ _POST ['body ' ],
46+ ]);
47+
48+ // redirect the user
49+ header ('location: /notes ' );
50+ die ();
0 commit comments