Skip to content

Instantly share code, notes, and snippets.

@dillingham
Last active February 3, 2021 03:43
Show Gist options
  • Save dillingham/95499ebe27c5d56c59ba9f5d5f2ae501 to your computer and use it in GitHub Desktop.
Save dillingham/95499ebe27c5d56c59ba9f5d5f2ae501 to your computer and use it in GitHub Desktop.
Route::macro('morph', function($models, $callable) {
  
    foreach($models as $model) {
        $name = class_basename($model);
        $base = Str::plural($name)."/{$name}";
        Route::prefix($base)->name("$name.")->group($callable);
    }
});
Route::morph([ \App\User::class ], function() {
  Route::get('comments', 'CommentController@index')->name('comments.index');
});

Produces /users/1/comments / user.comments.index

Useful to store morphable models in a package's config

  • "like" package users/{user}/likes

  • "comment" package users/{user}/comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment