1
+ <?php
2
+
3
+ /*
4
+ * Sometime too hot the eye of heaven shines
5
+ */
6
+
7
+ namespace App \Api \Controllers ;
8
+
9
+ use App \Http \Controllers \Controller ;
10
+ use App \Http \Requests \PostCreateRequest ;
11
+ use App \Http \Requests \PostUpdateRequest ;
12
+ use App \Post ;
13
+ use Carbon \Carbon ;
14
+ use Illuminate \Support \Facades \Auth ;
15
+ use Illuminate \Support \Facades \Storage ;
16
+
17
+ class PostController extends Controller
18
+ {
19
+ public function __construct ()
20
+ {
21
+
22
+ }
23
+
24
+ public function create (PostCreateRequest $ request )
25
+ {
26
+ //save post content to file
27
+ Storage::put ($ request ['title ' ].'.md ' , $ request ['content ' ]);
28
+
29
+ //db
30
+ if ($ post = Post::create (['title ' => $ request ['title ' ]])) {
31
+ $ postId = $ post ->id ;
32
+ return response ()->json (compact ('postId ' ));
33
+ }
34
+ }
35
+
36
+ public function index ()
37
+ {
38
+ $ posts = [];
39
+
40
+ //transform
41
+ foreach (Post::all () as $ key => $ value ) {
42
+ $ posts [$ key ]['id ' ] = $ value ['id ' ];
43
+ $ posts [$ key ]['title ' ] = $ value ['title ' ];
44
+ $ posts [$ key ]['date ' ] = Carbon::parse ($ value ['created_at ' ])->toDateString ();
45
+ }
46
+
47
+ return response ()->json (['data ' => $ posts ]);
48
+ }
49
+
50
+ public function show ($ id )
51
+ {
52
+ $ postRaw = Post::find ($ id );
53
+
54
+ //transform
55
+ $ post ['id ' ] = $ postRaw ['id ' ];
56
+ $ post ['title ' ] = $ postRaw ['title ' ];
57
+ $ post ['date ' ] = Carbon::parse ($ postRaw ['created_at ' ])->toDateString ();
58
+ $ post ['content ' ] = Storage::get ($ postRaw ['title ' ].'.md ' );
59
+
60
+ return response ()->json (['data ' => $ post ]);
61
+ }
62
+
63
+ public function update ($ id , PostUpdateRequest $ request )
64
+ {
65
+ $ post = Post::find ($ id );
66
+
67
+ //delete old file
68
+ Storage::delete ($ post ['title ' ].'.md ' );
69
+
70
+ //save new file
71
+ Storage::put ($ request ['title ' ].'.md ' , $ request ['content ' ]);
72
+
73
+ //update
74
+ if ($ post = $ post ->update (['title ' => $ request ['title ' ]])) {
75
+ return response ()->json (['data ' => ['postId ' => $ id ]]);
76
+ }
77
+
78
+
79
+ }
80
+
81
+ public function destroy ($ id )
82
+ {
83
+ if (Post::destroy ($ id )) {
84
+ return response ()->json ();
85
+ }
86
+ }
87
+ }
0 commit comments