In my Laravel application, I have the following index function in the PostController.php
class PostController extends Controller
{
private PostRepositoryInterface $postRepository;
public function __construct(PostRepositoryInterface $postRepository)
{
$this->postRepository = $postRepository;
}
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function index(): JsonResponse
{
return response()->json([
'data' => $this->postRepository->getAllPosts()
]);
}
}
Now, I want to display the data on my view called, posts.blade.php
Since I’m new to repository patterns on Laravel I’m struggling to call my view file from the controller.
How can I display my view file and display the JSON data in that view?
This is my web.php
Route::get('posts', [PostController::class, 'index']);
2
Answers
You’ve defined the
route
inweb.php
suggesting you’re accessing thisroute
via a web browser, yet yourindex
function has aJsonResponse
return type. Remove that return type as you won’t be returningJson
.N.B.
Personally I would do away with the repository and instead leverage
Eloquent
(part of the beauty and simplicity of Laravel). I feel it is one of those design patterns people blindly implement because they read an article or watched a YouTube video where someone said they should be using it. What is the likelihood you will ever change the underlying datasource for this project, is it just a redundant abstraction that does nothing but add implementation and maintenance overhead?