My question is: How do I tell my controller to sometimes return a view, and sometimes return JSON?
I created a resource controller called GameController . The Index method shows a list of all games the user has joined at the URL http://127.0.0.1/games.
class GameController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//Get all games user is part of
$games = Game::addSelect(...)->get();
return view('games.all', ['games', $games']);
}
...
}
This works great when I want to display a list of the users games in the browser.
Now I want to write some JavaScript to set up some event listeners, so that the user is notified when an event happens in their game. Something like below in app.js:
//Listen for some game events
$.get("/games", function( games ) {
for (let i = 0; i < games.length; i++) {
Echo.private(`Game.` + games[i]['id'] + `.Started`).listen('GameStarted', (e) => {
console.log('Game started');
});
}
}
The problem is my GameController::index method at the /games URL returns a view, when my JavaScript obviously needs the JSON.
So this brings me back to my question at the top of the page - how do I tell my controller to sometimes return a view, and sometimes return JSON?
I suspect this is where I need to start using the api.php routes, but I am unsure how to do this. Any code examples would be hugely appreciated. Thanks in advance!