2
votes

I am trying to wrap my head around the use cases of web routes and api routes.

So far, from what i understand

1) Web routes, are used when we want to return views.

2) Api routes, are used when we want to return json ( Api resource/collection ).

However both of these cases are referring to GET requests.

What about when we make a POST or PUT request, do we put these routes in api.php or web.php. Does it depend on whether the request is through an AJAX call ?

Additionally, i can't figure out in what cases should we use the api middleware and web middleware By default, the web.php uses web middleware, whereas the api.php uses the api middleware.

In the case where we are already signed in and we want to make an AJAX call, do we have to put that route in the api.php or web.php.

Do we use the api middleware only when we sign in using token based authentication ?

1

1 Answers

0
votes

Your same logic can be used to explain the use of POST or PUT requests for either types:

API routes

An API POST/PUT request would create/update some entity and return a JSON response, like a newly created model for POST, or an updated model for PUT.

return response()->json($model);

This is useful in cases where you have javascript code calling an AJAX request. When you'd send data to your API endpoint, you should receive a status 200 with a JSON representation of the model you just created/updated. Your javascript code then decides what to do next, like closing a popup window.

Web routes

A web POST/PUT request would also create/update some entity but would usually return a redirect to a new page:

session()->flash('alert', 'Model X has been updated!');
return redirect()->to('someurl');
// or
return redirect()->route('my.route.name');

POST/PUT Routes in your web.php are called using a simple <form action="..." method="POST'> form. Javascript is taken out of the equation here, so the form submission will send your form-data to the given endpoint, and it will return the response directly to your browser (which could be the view named my.route.name).