Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

elo's avatar
Level 3

Display API resource response data in a view

I have a simple bookstore laravel 5.7 app. I want to expose the app API also using laravel's api resources.

I am able to use the app features and also test the api endpoints on postman successfully but I am not convinced that way I have gone about it is the right way. Here is how I have gone about it

BookController

public function index()
{
    $books = Book::paginate(12);


    return view('welcome', compact('books'));
}

web.php

Route::get('/', 'BookController@index');

api.php

Route::get('/books', function() {
    return BookResource::collection(Book::with('ratings')->get());
});

Is it possible to use the BookResource in my controller so that

  1. I can return the welcome view along with the data
  2. I can display data in the view
  3. My api.php routes can be formatted like this Route::get('book', 'BookController@index')

Is this doable?

0 likes
9 replies
Tray2's avatar

Not really sure what it is you want to do but you can use the API to populate your views with the help of Vue.

elo's avatar
Level 3

@TRAY2 - My application isn't using vue right now. What I really want to do is return a books collection in my controller using the BookResource then display the books on the welcome page.

Calex's avatar
Calex
Best Answer
Level 8

If you want to use BookController@index for your views and your api, you could fetch the books using BookResource::collection() then use $request->wantsJson() to check if you should return the collection or the view. Something like that:

public function index(Request $request)
{
    // fetch a collection of books
    $books = BookResource::collection(...);
    
    if ($request->wantsJson())
    {
        return $books;
    }

    return view('welcome', compact('books'));
}
1 like
elo's avatar
Level 3

@CALEX - $request->wantsJson() that's something new to me. Educate me please, how is it used in this case? Let me search for it in the meantime

elo's avatar
Level 3

@CALEX - Couldn't find $request->wantsJson() in the 5.7 documentation. Tried the snippet but got the error message Undefined variable: request

Calex's avatar

@elo I updated the snippet, make sure to add the parameter to the index! I tested it with laravel 5.8 and $request->wantsJson() still exists.

1 like
elo's avatar
Level 3

@CALEX - Worked like a charm chief. I owe you a drink wink Interesting stuff I need to learn some more

1 like

Please or to participate in this conversation.