Can you have your own API and eat (consume) it in Laravel?

I created an API that returns json in Laravel. ( routes /api.php )

Now I want to use the specified API inside my web-side project ( routes / web.php (including middleware), types of lecture views , etc.) ..

The current solution 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 "redirects" the request to the api-analogue to my api, if the form is valid. But I have a feeling that this is not the best practice or smart. Other routes, besides loginand register, use the api token stored in the session to make calls. they add the "x-token" token as the title to $internal_request. Is it better to do this in middleware? Is there any example of a better implementation somewhere?

My API has a method like this:

POST api/register What check if the required fields exist and have a hard format (validation)

and my web route has /register

First check if the passwords match the password verification inputs (pass1 == pass2) and then pass them into the api equivalent.

So, there webshould be a superset (validation) api.

+4
2

, :

  • , API -
  • ( )
  • , web
  • api
  • json
+1

, api -, (a) - / (b) json API.

, : -, api, :

/web.php Route::post('/register', 'RegistrationController@register); `

/api.php Route::post('/register', 'RegistrationController@register) `

, (api/register /register ) .

:

public function register(Request $request) {
    if(!$request->expectsJson()) { // you may want to swap this with $request->isJson() depending on the HTTP headers for your app
        $this->validateWebRegistration($request); // your validation logic specific to web requests here
    }

    // common logic here (including validation); store result as $result

    if($request->expectsJson()) { // based on HTTP headers as above
        return response()->json($result);
    } else {
        return view('register', $result);
    }
}
+1

Source: https://habr.com/ru/post/1669825/


All Articles