1111use App \User ;
1212// 10: For Using sql queries
1313use DB ;
14+ use App \Http \Resources \PostsResource ;
1415
1516class PostsController extends Controller
1617{
@@ -21,7 +22,7 @@ class PostsController extends Controller
2122 */
2223 public function __construct ()
2324 {
24- $ this ->middleware ('auth ' , ['except ' => ['index ' , 'show ' ]]);
25+ $ this ->middleware ('auth ' , ['except ' => ['index ' , 'show ' , ' fetchall ' ]]);
2526 }
2627
2728 /**
@@ -41,10 +42,29 @@ public function index()
4142 //$posts = Post::orderBy('created_at', 'desc')->take(2)->get();
4243 // 13.1.4: For Pagination:
4344 $ posts = Post::orderBy ('created_at ' , 'desc ' )->paginate (5 );
44- // 10.1.2: return posts.index, @ 13.2: inject $posts
45+ // 10.1.2: return posts.index, @ 13.2: inject $posts:
4546 return view ('posts.index ' )->with ('posts ' , $ posts );
46-
47-
47+ }
48+
49+ /**
50+ * 10.1: Display a listing of the resource.
51+ *
52+ * @return PostsResource
53+ */
54+ public function fetchall ()
55+ {
56+ // 10.1.1: Using sql query to fetch all Posts:
57+ //$posts = DB::select('SELECT * FROM posts');
58+ // 13.1.1: Fetch all data using eleqouent:
59+ //$posts = Post::all();
60+ // 13.1.2: Order by Desc:
61+ //$posts = Post::orderBy('created_at', 'desc')->get();
62+ // 13.1.3: For Pulling limited records:
63+ //$posts = Post::orderBy('created_at', 'desc')->take(2)->get();
64+ // 13.1.4: For Pagination:
65+ $ posts = Post::orderBy ('created_at ' , 'desc ' )->paginate (5 );
66+ // 10.1.2: return posts.index, @ 13.2: inject $posts:
67+ return PostsResource::collection ($ posts );
4868 }
4969
5070 /**
@@ -127,6 +147,21 @@ public function show($id)
127147 // return Post::where('title', 'Post Two')->get();
128148 }
129149
150+ /**
151+ * 10.4: Display the specified resource.
152+ *
153+ * @param int $id
154+ * @return PostsResource
155+ */
156+ public function fetchone ($ id )
157+ {
158+ // 10.4.1: Find the post with id sent & return the entire post using eleqouent
159+ $ post = Post::findOrFail ($ id );
160+ return new PostsResource ($ post );
161+ // 10.4.2: To use where clause
162+ // return Post::where('title', 'Post Two')->get();
163+ }
164+
130165 /**
131166 * 10.5: Show the form for editing the specified resource.
132167 *
0 commit comments