phplaravelphp-curl

Call an API endpoint with Laravel controller


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.


Solution

  • 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.

    // web controller
    
    use App\Models\Task;
    
    public function show(Task $task){
        return view('task.show')->with(compact('task'));
    }
    

    Use Sanctum before creating your own token system.

    // routes/web.php
    
    Route::middleware('auth:sanctum')
         ->get('/task/{task}', [TaskDetailsController::class, 'show'])
         ->name('task.show');
    

    Http client doesn't appear anywhere.