0

I am calling internal API route from controller but unable set headers using laravel 8

$request = Request::create('/api/login/', 'POST',['id' => '1']);
$request->headers->set('Authorization','Basic YWJjOjEyMw==');//not working

$response = Route::dispatch($request);

print_r($response);
3
  • What do you want to achieve? It doesn't make sense at all to make an api call from controller. Commented Mar 18, 2023 at 18:15
  • Are you sure that it's not working? Try doing dd($request->headers->all()); before dispatching it and see if you can find your Authorization header. It should be there. Maybe it's something else that's failing. Maybe it should be Bearer instead of Basic? Commented Mar 18, 2023 at 18:34
  • Do not do this strange thing. Move code from controller to service and call service. Commented Mar 18, 2023 at 20:03

2 Answers 2

0

Have you tried using the Http facade for that?

use Illuminate\Support\Facades\Http;

$response = Http::withHeaders(['Authorization' => 'Basic ...'])->post('/api/login');

$json = $response->json();
$specific_field = $response->json('specific_field');
Sign up to request clarification or add additional context in comments.

4 Comments

with Http facade unable to call internal API
Try using the full url post(url('/api/login/'))
While calling my project via drive path working fine!. But while calling through php artisan serve URL getting timeout error
php artisan serve starts develpment server, that can handle only one request at time. So when you call api with Http facade, you are trying to start second request from the first and second needs to wait until first is complete, before it can run. And first can not complete, because it is waiting for second to complete, so you have created a deadlock.
0

if you want to sent an http request, try to use Guzzle HTTP client.

if it's not install in your Laravel project, install it via this command :

composer require guzzlehttp/guzzle

http get example :

use Illuminate\Support\Facades\Http;

$response = Http::get('http://example.com');

$response = Http::post('http://example.com/users', [
   'name' => 'Steve',
   'role' => 'Network Administrator',
]);

for more information visit Laravel doc here.

note: you should provide the full link. in my case in local and with the Laragon. I provide the following URL

 myproject.test/user/activity.

so in your case consider the port and the route url.it might be something like this:

localhost:8000/to/your/route

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.