Reputation: 4224
I'm writing a REST API and I'm using a polymorphic relationship to assign images to users
and products
(there will be more in the future and I intend the code to live long so I want to build something that will work for any other imageable
model).
So I have routes like this:
Route::resource('images', 'ImagesController');
Route::resource('products.images', 'ImagesController');
Route::resource('users.images', 'ImagesController');
So posting to /products/{id}/images
and /users/{id}/images
calls the same action: ImagesController::store( $resource_id )
. So I have everything to create the DB record, except for the parent model name!
My first guess was to use Route::current()->getName()
and work with the string part before the first "/" to get the model name. But is there a better, out-of-the-box way? Or I'm after the right track?
Upvotes: 3
Views: 2800
Reputation: 4224
Here's how I finally ended up doing it. Thanks to The Shift Exchange for the Request::segment(1)
part!
$parent_resource_class = studly_case( str_singular ( Request::segment(1) ) );
Upvotes: 1
Reputation: 60038
Just use the Laravel request segment function
$parent_resource = Request::segment(1);
// gives 'products' or 'users'
Upvotes: 4