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.
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
- I can return the
welcomeview along with the data - I can display data in the view
- My api.php routes can be formatted like this
Route::get('book', 'BookController@index')
Is this doable?
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'));
}
Please or to participate in this conversation.