skip to Main Content

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


  1. public function index()
    {
       $data = $this->postRepository->getAllPosts();
    
       if(request()->expectsJson){
          return response()->json([
          'data' => $data
          ]);
       }
    
       return view('VIEW_NAME', ['data' => $data]);
    }
    
    Login or Signup to reply.
  2. You’ve defined the route in web.php suggesting you’re accessing this route via a web browser, yet your index function has a JsonResponse return type. Remove that return type as you won’t be returning Json.

    class PostController extends Controller
    {
        private PostRepositoryInterface $postRepository;
    
        public function __construct(PostRepositoryInterface $postRepository)
        {
            $this->postRepository = $postRepository;
        }
    
        /**
         * Display a listing of the resource.
         */
        public function index()
        {
            return view('index', [
                'data' => $this->postRepository->getAllPosts()
            ]);
        }
    } 
    

    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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search