Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
La ruta de Laravel resuelve el tipo de datos personalizado

Tengo las siguientes rutas en routes/api.php :

 Route::get('items/{item}', function(Guid $item) {...}); Route::get('users/{user}', function(Guid $user) {...});

Dado que Guid es un tipo personalizado, ¿cómo puedo resolverlo mediante la inyección de dependencia ? Como se muestra, el parámetro de ruta {item} difiere del parámetro de devolución de llamada type-hint: Guid , por lo que no se puede resolver automáticamente.


Eso es lo que probé en app/Providers/AppServiceProvider.php :

 class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { $this->app->bind(Guid::class, function(Application $app, array $params) { return Guid::fromString($params[0]); }); } }

Esperaría que $params fuera algo como esto: [ 'item' => 'guid' ] -- pero es: [] .

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede hacer uso del enrutamiento de Laravel de enlace explícito :

en RouteServiceProvider::boot() :

 public function boot() { Route::model('item', Guid $item); Route::model('user', Guid $user); }

Si Guid no es un modelo, use un Closure para mapear en la cadena:

 Route::bind('user', function ($value) { return Guid::fromString($value); });

ACTUALIZADO

Y encontré otra forma, mucho mejor: implementar UrlRoutable contract Lavaravel API :

 <?php namespace App\Models; use Illuminate\Contracts\Routing\UrlRoutable; class Guid implements UrlRoutable { private string $guid; public function setGuid(string $guid) { $this->guid = $guid; return $this; } public function getGuid(): string { return $this->guid; } public static function fromString(string $guid): self { //you cannot set props from constructor in this case //because binder make new object of this class //or you can resolve constructor depts with "give" construction in ServiceProvider return (new self)->setGuid($guid); } public function getRouteKey() { return $this->guid; } public function getRouteKeyName() { return 'guid'; } public function resolveRouteBinding($value, $field = null) { //for using another "fields" check documentation //and maybe another resolving logic return self::fromString($value); } public function resolveChildRouteBinding($childType, $value, $field) { //or maybe you have relations return null; } }

Y, con esto, puede usar rutas como desee, ya que Guid ahora implementa UrlRoutable y puede convertir {item} (o lo que sea) marcadores de subcadena de ruta de URL en Guid s por inyección de dependencia (mediante la sugerencia de tipo que solicitó eso):

 Route::get('items/{item}', function(Guid $item) { return $item->getGuid(); });

Por cierto: NUNCA NUNCA use cierres en rutas ya que no puede almacenar en caché las rutas de cierre, y las rutas son buenas para optimizarse, y el almacenamiento en caché ayuda con eso en el enrutamiento de Laravel.

over 4 years ago · Santiago Trujillo Report

0

ayudante simple para utilizar la devolución de llamada de enlace de ruta.

 if (!function_exists('resolve_bind')) { function resolve_bind(string $key, mixed $value) { return call_user_func(Route::getBindingCallback($key), $value); } }

uso

 resolve_bind('key', 'value');
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!