Framework: Request: any and all routes

Created on 14 Jan 2013  路  5Comments  路  Source: laravel/framework

Well in L3 we could redirect any user request to a custom controller using Route::any('(:any), (:any)/(:all)', 'mycontroller@index');
With the changes in L4 i kinda see this idea lost, so please (re)implement the feature in L4.
I don't know a beautiful alternative to that problem in L4, i guess i could listen for 404 pages, get the values of the URL myself and start over there, but that's an ugly solution, if anyone knows any better ways, please tell me.

Most helpful comment

That's it, ty very much. +1

Route::any('{all}', function(){
    return 'It Works';
})->where('all', '.*');

All 5 comments

@DPr00f

Firstly, a 404 in L4 is handled by catching a Symfony\Component\HttpKernel\Exception\HttpNotFoundException so that's how you handle your 404's.

How you do the same in L4 is by appending where() after the declaration of a route, where the first parameter is the named param in the route and the second param is a regular expression which must match true. If it does not, the route is not executed and another match is found (if it exists). For example (don't quote me on syntax errors :P):

<?php

// GET /foo/123/some/other/value/here
// GET /foo/a123/sdf will not work as "a123" is not numeric.
Route::get('foo/{bar}/{baz}', function($bar, $baz)
{
    // $bar == 123
    // $baz == 'some/other/value/here'

})->where('bar', '\d+') // Digits
  ->where('baz', '.*');  // Anything

// You can modify your REGEX to suit:

// GET /foo/a123/asdf
// GET /foo/z123/asdf
// GEt /foo/df123/asdkfjsd
Route::get('foo/{bar}/{baz}', function($bar, $baz)
{

})->where('bar', '[a-z]{1,2}\d+') // 1-2 Letters + Digits
  ->where('baz', '.*');  // Anything

Have a look at http://symfony.com/doc/2.0/components/routing/introduction.html for more as L4 uses the Symfony routing as it's backbone.

Also, check out http://gskinner.com/RegExr/ for a really intuitive way to build up regular expressions :)

That's it, ty very much. +1

Route::any('{all}', function(){
    return 'It Works';
})->where('all', '.*');

No problem, glad I could help.

I was a bit disappointed to see (:all) go at first until I saw the potential of this solution!

I'd recommend closing the issue now :)

This is covered in the Laravel docs at four.laravel.com is it not? Also, @jasonlewis has a great blog post on this issue.

None of the above works in Laravel 4.0. Here is the solution:

Route::any('{firstPart}/{rest}', function($firstPart, $rest){
    return Response::make($firstPart . ", " . $rest);
})->where('firstPart', '[^/]*')->where('rest', '.*');
Was this page helpful?
0 / 5 - 0 ratings