I have made an API that returns json in Laravel. (routes/api.php)
Now I want to consume said API inside my web
-side of the project (routes/web.php (including middleware), blade views etc.).
The current solution that I have is something like this:
public function register(Request $request) {
// password1 == password2 etc (form logic / validation)
$internal_request = Request::create($this->base_api_url . 'register', 'POST');
$internal_request->replace($request->input());
$response = Route::dispatch($internal_request);
}
Which "forwards" the request to the api counterpart to my api if the form is valid. But I have the feeling this is not really best practice or smart. Other routes except login
and register
use the api token stored in session to make the calls. they append the token "x-token" as a header to $internal_request
. Is it better to do this in middleware? Is there some example of a best implementation somewhere?
My API has a method like this:
POST api/register
Which check if the the required fields exist and have the rigt format (validation)
and my web route has /register
This will first check if the passwords match from the password validation inputs (pass1 == pass2) and will then pass it to the api equivalent.
So web
should be a superset (validation wise) of api
.
I think I will do it this way:
As I understand your question, you want to apply the same logic to both api and web requests and you may just want to (a) validate the form for a web request and/or (b) wrap the response in json for an API request.
I think the best way to do this would be to refer to the same controller and method for both web and api requests, so for example:
In your routes/web.php, add
Route::post('/register', 'RegistrationController@register
);`And in your routes/api.php, add
Route::post('/register', 'RegistrationController@register
)`So eventually both requests (api/register and /register) hit the same controller and method.
Now, in your controller, you can perform the extra actions depending on request like so: