I am trying to send some data to my admin dashboard page. The data is for two charts: the first displays the number of articles posted by users in the past week and the other displays the last five articles. However, each of these datas are returned from separate methods of my controller. So far, I have fetched all the data I need from the database in one method and returned a view with all the data, In this way:
return view('admin', compact('lastUserPosts'))->with('week', json_encode($week))
->with('postNo', json_encode($postNo));
and a normal route like:
Route::get('/dashboard', [App\Http\Controllers\DashboardController::class, 'index'])->name('dashboard');
clearly I'm not following the single responsibility principle, so I'm wondering How can I write my code to fetch each set of data from its own method in controller and then call both of these methods in one route.
CodePudding user response:
I would highly recommend that you watch Laracon EU conference there was a talk titled becoming a better developer by using the SOLID principles, aside from that what you can do is separate the logic of the contoller from formatting and fetching the data by creating a middle layer between it and the model something like a PostsRepository now this class should contain the fetching and ajax formating of the Model, import it in your contoller use App\Repository\PostsRepository and instead of the normal model that you enject to your controller method use the Repository instead
Public function getAllPosts( PostsRepository $post) {
.....
}
Now you have access to all the method of the Post model from a different class and you can also test it easily
