When I do php artisan routes, the GET request of my app has a |HEAD. What is the purpose of having |HEAD?
Routes.php
+--------+----------------------------------+------------------------------+--------------------------------------+----------------+---------------+
| Domain | URI | Name | Action | Before Filters | After Filters |
+--------+----------------------------------+------------------------------+--------------------------------------+----------------+---------------+
| | GET|HEAD / | home | HomeController#home | | |
| | GET|HEAD user/{username} | profile-user | ProfileController#user | | |
| | GET|HEAD account/change-password | account-change-password | AccountController#getChangePassword | auth | |
| | GET|HEAD asset/encode-file/{id} | encode-file | EncodeController#getEncode | auth | |
| | GET|HEAD asset/edit-file/{id} | edit-file | AssetController#getEdit | auth | |
| | GET|HEAD asset/delete-file/{id} | delete-file | AssetController#deleteDestroy | auth | |
| | GET|HEAD asset/upload-file-form | upload-file-form | AssetController#getUploadCreate | auth | |
| | GET|HEAD asset/library | asset-library | AssetController#getAssetLib | auth | |
| | GET|HEAD account/sign-out | account-sign-out | AccountController#getSignOut | auth | |
| | GET|HEAD account/activate/{code} | account-activate | AccountController#getActivate | guest | |
| | GET|HEAD account/forgot-password | account-forgot-password | AccountController#getForgotPassword | guest | |
| | GET|HEAD account/recover/{code} | account-recover | AccountController#getRecover | guest | |
| | GET|HEAD account/sign-in | account-sign-in | AccountController#getSignIn | guest | |
| | GET|HEAD account/create | account-create | AccountController#getCreate | guest | |
+--------+----------------------------------+------------------------------+--------------------------------------+----------------+---------------+
The HEAD request is almost identical to a GET request, they only differ by a single fundamental aspect: the HEAD response should not include a payload (the actual data).
This makes the HEAD HTTP verb fundamental for managing the validity of your current cached data.
The value for a header field in the response of your HEAD request will warn you if your data is not up-to-date. After that you can make a proper GET request retrieving the updated data.
This can be achieved observing the Content-Length field or the Last-Modified field for example.
When working with large payloads, caching your data and making HEAD requests before the actual GET to check the validity of you current data can save you big money on data consumption.
You will know precisely when to retrieve the full payload.
The big question is: why is Laravel combining HEAD and GET HTTP verbs when you use Route::get()?
You can use Route::match('HEAD') to register your HEAD request, but I find it weird that we don't have Route::head().
From the HTTP RFC:
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.
Following function is taken from the Laravel's Illuminate\Routing\Router.php class, when you use Route::get() method to add a route for your site/application, Laravel adds both methods for the url, it means that, these urls registered using getmethod could be accessed using both GET and HEAD HTTP method, and HEAD is just another HTTP verb/method, used for making a HEAD request.
/**
* Register a new GET route with the router.
*
* #param string $uri
* #param \Closure|array|string $action
* #return \Illuminate\Routing\Route
*/
public function get($uri, $action)
{
return $this->addRoute(array('GET', 'HEAD'), $uri, $action);
}
Related
I am trying to integrate Spring Auth Server with an existing authentication provider, IBM WebSeal in the context of an OICD flow.
Basically, I want Spring Auth Server to use Webseal login page to authenticate a user (coming from a SPA/front-end app) and then return a JWT token to the front-end app.
On successful authentication, WebSeal redirects to a configurable URL adding a header to the request. This header contains the actual username and signals that the user is authenticated.
I was able to implement the flow and have Spring Auth Server use the external login page, but I don't understand to which URL should WebSeal redirect. Do I need to create an explicit end-point (such as /authenticated)?
It seems that the OAUTH2 spec doesn't define an explicit endpoint for this particular case.
Adding diagram for clarity:
+----------------+ +------------------+
| | | |
| | | |
| FRONT END APP | | BACK-END APP |
| | | (SPRING BOOT) |
| | | |
| | | |
+---|----|-------+ +------------------+
| |
4 - /oauth2/token | | 1 - /oauth2/authorize?
| |
| |
| |
+---|----|-------+ +----------------+
| | 3 - send header | |
| SPRING -------------------- |
| AUTH | | WEBSEAL |
| SERVER -------------------| |
| | 2 - show form | |
| | +----------------+
+----------------+
Thanks!
So I got a template of a Flutter app that retrieves all its data from a website using HTTP get requests.
I have the following method that gets the list of resturaunts:
Future<Stream<Restaurant>> getNearRestaurants(LocationData myLocation, LocationData areaLocation) async {
String _nearParams = '';
String _orderLimitParam = '';
if (myLocation != null && areaLocation != null) {
_orderLimitParam = 'orderBy=area&limit=5';
_nearParams = '&myLon=${myLocation.longitude}&myLat=${myLocation.latitude}&areaLon=${areaLocation.longitude}&areaLat=${areaLocation.latitude}';
}
final String url = '${GlobalConfiguration().getString('api_base_url')}restaurants?$_nearParams&$_orderLimitParam';
final client = new http.Client();
final streamedRest = await client.send(http.Request('get', Uri.parse(url)));
return streamedRest.stream.transform(utf8.decoder).transform(json.decoder).map((data) => Helper.getData(data)).expand((data) => (data as List)).map((data) {
return Restaurant.fromJSON(data);
});
}
However when I swap the template's url variable for my own website, the app gets stuck and streamRest returns with an error 404 page.
Tried Solutions:
I surrounded it with a try/catch block and it gave me no exceptions.
I also installed postman and checked my website with the GET statement for the same list of restaurants I try to retrieve in the flutter code posted above and see this: Postman GET screenshot
Its as if my website cannot route to the specific pages in my API folder. But they are all defined in api.php.
Update 1:
My web.php looks like this https://pastebin.com/QRG300uL. It seems to be similar to what was suggested below
Update 2:
I ran php artisan route::list and it showed that all the routes seem to be there:
| | POST | api/restaurant_reviews | restaurant_reviews.store | App\Http\Controllers\API\RestaurantReviewAPIController#store | api |
| | GET|HEAD | api/restaurant_reviews | restaurant_reviews.index | App\Http\Controllers\API\RestaurantReviewAPIController#index | api |
| | GET|HEAD | api/restaurant_reviews/create | restaurant_reviews.create | App\Http\Controllers\API\RestaurantReviewAPIController#create | api |
| | DELETE | api/restaurant_reviews/{restaurant_review} | restaurant_reviews.destroy | App\Http\Controllers\API\RestaurantReviewAPIController#destroy | api |
| | GET|HEAD | api/restaurant_reviews/{restaurant_review} | restaurant_reviews.show | App\Http\Controllers\API\RestaurantReviewAPIController#show | api |
| | PUT|PATCH | api/restaurant_reviews/{restaurant_review} | restaurant_reviews.update | App\Http\Controllers\API\RestaurantReviewAPIController#update | api |
| | GET|HEAD | api/restaurant_reviews/{restaurant_review}/edit | restaurant_reviews.edit | App\Http\Controllers\API\RestaurantReviewAPIController#edit | api |
| | GET|HEAD | api/restaurants | restaurants.index | App\Http\Controllers\API\RestaurantAPIController#index | api |
| | POST | api/restaurants | restaurants.store | App\Http\Controllers\API\RestaurantAPIController#store | api |
| | GET|HEAD | api/restaurants/create | restaurants.create | App\Http\Controllers\API\RestaurantAPIController#create | api |
| | GET|HEAD | api/restaurants/{restaurant} | restaurants.show | App\Http\Controllers\API\RestaurantAPIController#show | api |
| | DELETE | api/restaurants/{restaurant} | restaurants.destroy | App\Http\Controllers\API\RestaurantAPIController#destroy | api |
| | PUT|PATCH | api/restaurants/{restaurant} | restaurants.update | App\Http\Controllers\API\RestaurantAPIController#update | api |
| | GET|HEAD | api/restaurants/{restaurant}/edit | restaurants.edit | App\Http\Controllers\API\RestaurantAPIController#edit | api |
| | POST | api/send_reset_link_email | | App\Http\Controllers\API\UserAPIController#sendResetLinkEmail | api |
| | GET|HEAD | api/settings | | App\Http\Controllers\API\UserAPIController#settings | api |
Solution:
This worked for me after changing alot of things, I changed my GET request url from "www.domain.com/api/resturants" to "www.domain.com/public/api/resturants"
Well i don't know about your flutter code for i use different methods in retrieving data from api but about the routes i suggest you do like me
in web.php the route file
//Api routes
Route::get('/company/api/fetch', 'ApiController#fetch_companies');
my api controller
public function fetch_companies()
{
$companies = Companies::all();
return response()->json($companies);
}
this way you will get the data passed to the route /company/api/fetch (you can modify that as you want) and when a get request enter this page it will return json
and for the request handling in flutter side i suggest you make your functions and classes as it is in the documentations
Note: that the flutter solution that i suggested may not work with your case for you are using Stream which is different than this type of requests because this type runs only ones while the Stream runs many times and gets data every time it gets new data from the server
I'm developing an API with Laravel 6.
I've got 2 models:
card -> table cards with card_id ecc.
user -> table users with user_id ecc.
I've defined into models many to many relationships
User.php
public function cards()
{
return $this->belongsToMany('App\Models\v1\Card');
}
Card.php
public function users() {
return $this->belongsToMany('App\Models\v1\User');
}
The pivot table is called card_user .
Now I've created routes for single entities:
Route::resource('v1/users', 'v1\UsersController');
Route::resource('v1/cards', 'v1\CardsController');
and I need to develop routes and controller for insert and delete rows from pivot table.
What is the best practice for this issue?
I try to solve this with a special controller that respond to a specific endpoint:
Route::resource('v1/cards/{id}/users', 'v1\CardsUsersController')->only([
'index', 'store', 'destroy'
]);
But when I need to store information I need to pass the ids of card and user into the URL and as object in post body like so:
[
'user_id' => $userId,
'card_id' => $cardId
]
Exists a better way to do this?
Thanks a lot!
You can use Nested Resources as described here:
https://laravel.com/docs/6.x/controllers#restful-nested-resources
"Sometimes you may need to define routes to a "nested" resource. For example, a photo resource may have multiple "comments" that may be attached to the photo. To "nest" resource controllers, use "dot" notation in your route declaration:
Route::resource('photos.comments', 'PhotoCommentController');
This route will register a "nested" resource that may be accessed with URLs like the following: photos/{photos}/comments/{comments}."
If you must have separate routes and controller for them, then it would be better to do
Route::resource('v1/card_user', 'v1\CardsUsersController')->only(['index', 'store','destroy']);
Keep the route clean, and don't overcomplicate it. Either You or someone else in the future who views code should be able to understand what it is for.
I would combine both answers. As a relationship, it is technically a nested resource. Also, you really have 2 RESTful actions: store and destroy (which correspond to attach and detach in Laravel). You may also want an index to view all of the relationship. I believe the "create" action is optional, depending on your UI.
// Ability_Role pivot routes
Route::resource('v1/user.cards', 'UserCardController')
->only(['index', 'create', 'store','destroy']);
This will give the following routes:
+--------+----------+------------------------------+--------------------+-------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+------------------------------+--------------------+-------------------------------------------------+------------+
| | GET|HEAD | v1/user/{user}/cards | user.cards.index | App\Http\Controllers\UserCardController#index | web |
| | POST | v1/user/{user}/cards | user.cards.store | App\Http\Controllers\UserCardController#store | web |
| | GET|HEAD | v1/user/{user}/cards/create | user.cards.create | App\Http\Controllers\UserCardController#create | web |
| | DELETE | v1/user/{user}/cards/{card} | user.cards.destroy | App\Http\Controllers\UserCardController#destroy | web |
+--------+----------+------------------------------+--------------------+-------------------------------------------------+------------+
I chose to label the routes as user.cards because I would think you would more often want to start with the user model and attached the cards.
For the store method, you can post an array of cards to attached to the user.
If you also want to start with cards, and store an array of users, you can also define the inverse relationships (though it would require a 2nd controller with just the create and store routes:
// Inverse create and store routes
Route::get('v1/cards/{card}/users/create', 'CardUserController#create')
->name('cards.users.create');
Route::post('v1/cards/{card}/users', 'CardUserController#store')
->name('cards.users.store');
now you will get 2 more routes added:
+--------+----------+------------------------------+--------------------+-------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+------------------------------+--------------------+-------------------------------------------------+------------+
| | GET|HEAD | api/user | api. | Closure | api |
| | | | | | auth:api |
| | POST | v1/cards/{card}/users | cards.users.store | App\Http\Controllers\CardUserController#store | web |
| | GET|HEAD | v1/cards/{card}/users/create | cards.users.create | App\Http\Controllers\CardUserController#create | web |
| | GET|HEAD | v1/user/{user}/cards | user.cards.index | App\Http\Controllers\UserCardController#index | web |
| | POST | v1/user/{user}/cards | user.cards.store | App\Http\Controllers\UserCardController#store | web |
| | GET|HEAD | v1/user/{user}/cards/create | user.cards.create | App\Http\Controllers\UserCardController#create | web |
| | DELETE | v1/user/{user}/cards/{card} | user.cards.destroy | App\Http\Controllers\UserCardController#destroy | web |
+--------+----------+------------------------------+--------------------+-------------------------------------------------+------------+
I am trying to set up a Route:resource for Series.
When I create individual get, post, patch and delete Routes it works as expected (e.g. GET series/${serie}).
However when I use Route::resource it creates plural attributes (e.g. GET series/${series}).
In the laracast that I am following it creates the singular (e.g. GET projects/${project}).
I can't figure out what I am missing.
This works:
Route::get('/series', 'SeriesController#index');
Route::get('/series/create', 'SeriesController#create');
Route::get('/series/{serie}', 'SeriesController#show');
Route::post('/series', 'SeriesController#store');
Route::get('/series/{serie}/edit', 'SeriesController#edit');
Route::patch('/series/{serie}', 'SeriesController#update');
Route::delete('/series/{serie}', 'SeriesController#destroy');
The route list is:
GET|HEAD | series | App\Http\Controllers\SeriesController#index
POST | series | App\Http\Controllers\SeriesController#store
GET|HEAD | series/create | App\Http\Controllers\SeriesController#create
GET|HEAD | series/{serie} | App\Http\Controllers\SeriesController#show
PATCH | series/{serie} | App\Http\Controllers\SeriesController#update
DELETE | series/{serie} | App\Http\Controllers\SeriesController#destroy
GET|HEAD | series/{serie}/edit | App\Http\Controllers\SeriesController#edit
This doesn't work:
Route::resource('series', 'SeriesController');
and produces this route list:
GET|HEAD | series | App\Http\Controllers\SeriesController#index
POST | series | App\Http\Controllers\SeriesController#store
GET|HEAD | series/create | App\Http\Controllers\SeriesController#create
GET|HEAD | series/{series} | App\Http\Controllers\SeriesController#show
PATCH | series/{series} | App\Http\Controllers\SeriesController#update
DELETE | series/{series} | App\Http\Controllers\SeriesController#destroy
GET|HEAD | series/{series}/edit | App\Http\Controllers\SeriesController#edit
Notice the plural form {series}. Why is this happening?
"Series" is the plural as well as the singular of the word, therefore the routes Laravel is generating are perfectly fine.
If you have a look into Laravels pluralizer helper, you can even see that "series" is explicitely listed as uncountable: https://github.com/laravel/framework/blob/5.5/src/Illuminate/Support/Pluralizer.php#L49
I've defined the following route in Laravel:
Route::group(['prefix' => 'api'], function() {
Route::post('login', [
'uses' => 'Auth\AuthController#login',
'as' => 'auth.login',
]);
});
And I'm using Postman to send a request like this (you can also see the results):
Why am I getting a MethodNotAllowed exception????
I also tried creating a form in an empty html file, with the method set to post. but got the same results.
EDIT
If i add a route::get that shows a login form, after the post request in Postman it shows that login form.
EDIT 2:
output of php artisan route:list for our route entries:
+--------+----------+--------------+---------------------+----------------------------------------------------+------------+
| Domain | Method | URI | Name | Action | Middleware |
+--------+----------+--------------+---------------------+----------------------------------------------------+------------+
| | GET|HEAD | / | guest.home | App\Http\Controllers\GuestController#index | |
| | GET|HEAD | a/dashboard | admin.dashboard | Closure | |
| | POST | api/login | auth.login | App\Http\Controllers\Auth\AuthController#login | |
| | GET|HEAD | api/login | auth.login | Closure | |
| | GET|HEAD | api/logout | auth.logout | App\Http\Controllers\Auth\AuthController#getLogout | jwt.auth |
| | POST | api/register | auth.register | App\Http\Controllers\Auth\AuthController#register | jwt.auth |
| | GET|HEAD | m/dashboard | moderator.dashboard | Closure | |
| | GET|HEAD | pu/dashboard | premium.dashboard | Closure | |
| | GET|HEAD | u/dashboard | user.dashboard | Closure | |
+--------+----------+--------------+---------------------+----------------------------------------------------+------------+
EDIT3
One more curious thing. If i set the method to Route::any, I get rid of the exception, but then I can't access the post parameters. i.e. I don't have any post parameters.
EDIT 4:
If I add a route::get and show the login view there and send the login credential, it works. But not in Postman.
Use x-www-form-urlencoded instead of form-data in postman, See the difference below.
form-data
multipart/form-data is the default encoding a web form uses to transfer data. This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.
urlencoded
This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.
Unfortunately the problem was with Postman3. I'm using Advanced REST Client now, and it works alright. Postman would send GET requests no matter what method I chose.