0

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.

1
  • 1
    why would you ever need to hit an endpoint on your application from WITHIN your application? Commented Apr 29, 2024 at 13:38

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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".).

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.