Create Class Rules

You can create custom class rules with two main options: a generator class, or ad-hoc.

Create Generator Class

The generator class is the preferred method of adding new rules. Generator classes live in one location, so they promote good code maintenance.

Add A Generator

First decide where you will place your custom generators. For the purpose of this example, we will use app/Providers/RouteToClass/ to store all of our generators.


namespace App\Providers\RouteToClass;

use Zschuessler\RouteToClass\Generators\GeneratorAbstract;

class UserTypeGenerator extends GeneratorAbstract
    public function generateClassName()
        // Use your own logic here to determine user type 
        $userType = 'admin';

        return 'user-' . $userType;

As you can see above, all you need to do is extend the GeneratorAbstract class and implement a generateClassName method which returns a string. Simple!

Register Generator in Config

Now add the following line to the route2class.php configuration:



See Included Example Generator

Example generator included in the package is here:

Ad-Hoc Implementations

You aren't forced to use a class generator, although it's preferred. Simply call the addClass method of the package facade to add any number of custom classes.

The example below adds classes based on a route - but you can add these calls anywhere in your application (controllers, models, etc):

Route::get('/', function () {
    // Add static class as string

    // Add class from anonymous function
    Route2Class::addClass(function() {
        // Your custom logic goes here
        return 'my-anon-class-name';

    return view('welcome');