Hamed Hamed - 6 months ago 122
PHP Question

Dynamic routes in laravel instead of manual routes

I want to prevent write all route in laravel route.php,actually i follow MVC routing like this www.example.com/controller/action/p1/p2/p3
if you have any good idea give it to me,
i wrote this

$controller = ucfirst(Request::segment(1));
$controller = $controller . 'Controller';
$result=App::make('indexController')->ChechIfExistController($controller);
if($result){
if(Request::segment(2))
$action=Request::segment(2);
else
$action='index';

if(Request::segment(5))
Route::any('/{controller?}/{action?}/{p1?}/{p2?}/{p3?}',array('uses'=>$controller.'@'.$action));
else if(Request::segment(4))
Route::any('/{controller?}/{action?}/{p1?}/{p2?}',array('uses'=>$controller.'@'.$action));
else if(Request::segment(3))
Route::any('/{controller?}/{action?}/{p1?}',array('uses'=>$controller.'@'.$action));
else
Route::any('/{controller?}/{action?}',array('uses'=>$controller.'@'.$action));

} else{
echo '404';
EXIT;

}


but i donot know how to control and check controller and action in laravel to understand if it exist or not.
i need your help.
thanks a lot.

ifound it,this code fix the problem and check if action exist or not,but i would like to do that with laravel but it seems laravl does not have any thing for checking controller and actions

$controller=='Controller'?$controller='IndexController':$controller;

$controllers=new $controller ();

if(method_exists($controllers,$action)){...}


and in composer define my route,
that's all

Answer

routes.php

Route::controllers([
    'auth' => 'Auth\AuthController',
]);

in AuthController you can do that:

// will be available as METHODNAME /auth/url/{one?}/{two?}/{three?}/{four?}/{five?}
public [methodName]Url($one, $two, $three, $four, $five)
{
   //...
}

// for example POST /auth/register
public function postRegister(Request $request)
{
    // ...
}

// GET /auth/login
public function getLogin()
{
    //...
}

it's not documented, but you can see that in sources: https://github.com/laravel/framework/blob/5.0/src%2FIlluminate%2FRouting%2FControllerInspector.php https://github.com/laravel/framework/blob/5.0/src%2FIlluminate%2FRouting%2FRouter.php#L238

Comments