My Laravel API is running on 127:0.0.1:8000.
Now I want to call to this API
Route::get('/task/{task_id}', [TaskDetailsController::class, 'index']);
from my web controller
This is the function where I wrote to call that API
public function index($task, $token)
{
$tokens = Token::where('token', $token)->first();
$tasks = Task::find($task);
$apiUrl = url('/api/task/'.$task);
if ($tokens && $tasks){
$response = Http::withHeaders([
'Authorization' => 'Bearer ' . $token,
])->get(''.$apiUrl);
if ($response->successful()) {
dd($response->json());
} else {
dd("failed");
}
}
else{
dd("baal");
}
}
but I get this error
cURL error 28: Operation timed out after 30002 milliseconds with 0 bytes received (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for http://localhost:8000/api/task/11
I have tried to write raw PHP code and use guzzle http package
but didn’t get the fix.
2
Answers
Your index function within the controller requires two parameters ($tasks and $tokens); therefore, your API endpoint has to include two parameters (task_id and token). So, you have to change your code like the following:
Route::get("/index/{task_id}/{token}", [TaskDetailsController::class, "index"]);
After these changes, you have to enter two parameters (task_id and token) to the URL (For instance, "http://127.0.0.1:8000/2/your_token".).
Laravel Http client is not used to make requests to own API.
Use for external API.
Learn the standard usage of Laravel.
You can use Eloquent directly.
Use Sanctum before creating your own token system.
Http client doesn’t appear anywhere.