F
Filament12mo ago
lupoz

How can I call a API route in a form?

I need to compile a text area with some data via Ajax. I cheated a controller that collect the data and a route for call the controller. How can implement that in a FIlament form?
2 Replies
LeandroFerreira
LeandroFerreira12mo ago
There are field hydration, update, that you can use https://filamentphp.com/docs/3.x/forms/advanced#field-hydration Maybe this can help you
lupoz
lupozOP12mo ago
I tried: Filament:
TextInput::make('name')

->required()
->afterStateUpdated(fn ($state, callable $ChatGPT) => [
$ChatGPT('full_description', $ChatGPT($state)),
]),

MarkdownEditor::make('full_description')
TextInput::make('name')

->required()
->afterStateUpdated(fn ($state, callable $ChatGPT) => [
$ChatGPT('full_description', $ChatGPT($state)),
]),

MarkdownEditor::make('full_description')
Route:
Route::post('/chat', ChatGPT::class)->name('ChatGPT');
Route::post('/chat', ChatGPT::class)->name('ChatGPT');
Controller:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Throwable;

class ChatGPT extends Controller
{
/**
* @param Request $request
* @return string
*/
public function __invoke(Request $request): string
{

try {
/** @var array $response */
$response = Http::withHeaders([
"Content-Type" => "application/json",
"Authorization" => "Bearer " . env('CHAT_GPT_KEY')
])->post('https://api.openai.com/v1/chat/completions', [
"model" => $request->post('model'),
"messages" => [
[
"role" => "user",
"content" => $request->post('content')
]
],
"temperature" => 0,
"max_tokens" => 2048
])->body();
return $response['choices'][0]['message']['content'];
} catch (Throwable $e) {
return "Error: $e";
}
}
}
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Throwable;

class ChatGPT extends Controller
{
/**
* @param Request $request
* @return string
*/
public function __invoke(Request $request): string
{

try {
/** @var array $response */
$response = Http::withHeaders([
"Content-Type" => "application/json",
"Authorization" => "Bearer " . env('CHAT_GPT_KEY')
])->post('https://api.openai.com/v1/chat/completions', [
"model" => $request->post('model'),
"messages" => [
[
"role" => "user",
"content" => $request->post('content')
]
],
"temperature" => 0,
"max_tokens" => 2048
])->body();
return $response['choices'][0]['message']['content'];
} catch (Throwable $e) {
return "Error: $e";
}
}
}
Error: An attempt was made to evaluate a closure for [Filament\Forms\Components\TextInput], but [$ChatGPT] was unresolvable.
Want results from more Discord servers?
Add your server