Yes, you can use custom route model binding in Laravel to bind a route parameter to a model retrieved from an external API like Pipedrive. Since your model isn't an Eloquent model, you'll need to create a custom binding resolver. Here's how you can do it:
-
Create a Custom Model Class:
First, create a class that represents the model you want to bind. This class will hold the data you retrieve from the API.
class PipedriveModel { public $id; public $name; // Add other properties as needed public function __construct($data) { $this->id = $data['id']; $this->name = $data['name']; // Initialize other properties } } -
Create a Service to Fetch Data from the API:
Create a service class that will handle the HTTP request to the Pipedrive API.
use Illuminate\Support\Facades\Http; class PipedriveService { public function find($id) { $response = Http::get("https://api.pipedrive.com/v1/your-endpoint/{$id}", [ 'api_token' => 'your_api_token', ]); if ($response->successful()) { return new PipedriveModel($response->json()['data']); } return null; } } -
Register the Custom Binding in a Service Provider:
In your
AppServiceProvideror a dedicated service provider, register the custom binding.use Illuminate\Support\Facades\Route; use App\Services\PipedriveService; use App\Models\PipedriveModel; public function boot() { Route::bind('pipedriveModel', function ($value) { $service = new PipedriveService(); return $service->find($value); }); } -
Define Your Route:
Use the custom binding in your route definition.
use App\Models\PipedriveModel; Route::get('/pipedrive/{pipedriveModel}', function (PipedriveModel $pipedriveModel) { return response()->json($pipedriveModel); });
With this setup, when you access a route like /pipedrive/123, Laravel will automatically resolve the 123 parameter using your custom binding logic, fetch the data from the Pipedrive API, and inject an instance of PipedriveModel into your route's closure or controller method.