samedi 27 mai 2017

Laravel dynamically resolve model type from route

Is there a way in Laravel 5.4 that if I pass in from a route the name of an object say product so /api/requests/product or /api/requests/item

The issue is that I can't typehint from the route as my route looks like this:

Route::post('/requests/{type}', 'RequestsController@store');

I thought that I could use a switch case in the store method like so:

 public function store($type)
    {
       switch ($type) {
           case Product::class:
               $model = new Product();
               break;
           case Item::class:
               $model = new Item();
               break;
           default: 
               throw new Exception('Cannot resolve model from request type');
       }

    }

However for a larger application, this would become very clunky. Is there a better way to approach this problem perhaps using reflection or the IoC?

Any help is appreciated.

Thanks



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire