Laravel 4 Custom Package Routes

Get the same bundle 'handles' functionality as in Laravel 3

I've been playing around with Laravel 4 a bit recently, looking to port my Laravel 3 auth bundle, Verify across pretty soon.

While playing around with packages (the new bundles), the documentation read like you couldn't let the user decide how to route the package anymore.

In prior versions of Laravel, a handles clause was used to specify which URIs a package could respond to. However, in Laravel 4, a package may respond to any URI.
Laravel 4 docs

I quite liked this feature in Laravel 3; it meant you could create an admin bundle, for instance, and allow the user to choose how they accessed it.

Putting handles back in

This code below assumes you know how to create packages for Laravel 4. If you don't, have a look at this great packages tutorial!

First, add a handles key to your package config:

return array(
    'handles' => 'url'
);

This is exactly the same syntax as the handles key/value in your bundles.php file for Laravel 3.

Secondly, create your routes.php file:

// Get the handles config item
$handles = Config::get('package::handles');

// Make sure a trailing is at the end
$handles = rtrim($handles, '/').'/';

Route::get($handles.'slug', function() {
    return 'Hello';
});

I placed my routes.php file in src, but you can place it anywhere really.

Then, in the boot method (not the register method, as the Laravel 4 docs mention), include your routes:

public function boot()
{
    $this->package('vendor/package');

    require_once __DIR__.'/../../routes.php';
}

The reason we use the boot method is because we need access to the package config, which we don't have at the register phase.

That's it! If you go to /url/slug (if you've copied the example), you should see 'Hello'.

So that's how can now let the user route your package however they want. They can even leave the handles value blank, and it'll just route straight off your site URL!

Want to let me know what you think of Laravel 4 Custom Package Routes? Why not leave a comment, follow me on Twitter , or !

Comments

comments powered by Disqus