Laravel Creating Dynamic Routes to controllers from Mysql database

后端 未结 5 645
无人及你
无人及你 2020-12-07 11:14

I have the following table: group_pages in mysql database with page name route name :

   id   name      route
  --------------------
    0   About      about         


        
5条回答
  •  抹茶落季
    2020-12-07 12:07

    After spending 2 hours, digging through google and Laravel source, I came up with this solution, which I think works the best and looks the cleanest. No need for redirects and multiple inner requests.

    You add this route at the very bottom of routes files. If no other routes are matched, this is executed. In the closure, you decide which controller and action to execute. The best part is - all route parameters are passed to action, and method injection still works. The ControllerDispatcer line is from Laravel Route(r?) class.

    My example would handle 2 cases - first checks if user exists by that name, then checks if an article can be found by the slug.

    Laravel 5.2 (5.3 below)

    Route::get('{slug}/{slug2?}', function ($slug) {
        $class = false;
        $action = false;
    
        $user = UserModel::where('slug', $slug)->first();
        if ($user) {
            $class = UserController::class;
            $action = 'userProfile';
        }
    
        if (!$class) {
            $article= ArticleModel::where('slug', $slug)->first();
            if ($article) {
                $class = ArticleController::class;
                $action = 'index';
            }
        }
    
        if ($class) {
            $route = app(\Illuminate\Routing\Route::class);
            $request = app(\Illuminate\Http\Request::class);
            $router = app(\Illuminate\Routing\Router::class);
            $container = app(\Illuminate\Container\Container::class);
            return (new ControllerDispatcher($router, $container))->dispatch($route, $request, $class, $action);
        }
    
        // Some fallback to 404
        throw new NotFoundHttpException;
    });
    

    5.3 has changed how the controller gets dispatched.

    Heres my dynamic controller example for 5.3, 5.4

    namespace App\Http\Controllers;
    
    
    use Illuminate\Routing\Controller;
    use Illuminate\Routing\ControllerDispatcher;
    use Illuminate\Routing\Route;
    
    class DynamicRouteController extends Controller
    {
        /**
         * This method handles dynamic routes when route can begin with a category or a user profile name.
         * /women/t-shirts vs /user-slug/product/something
         *
         * @param $slug1
         * @param null $slug2
         * @return mixed
         */
        public function handle($slug1, $slug2 = null)
        {
            $controller = DefaultController::class;
            $action = 'index';
    
            if ($slug1 == 'something') {
                $controller = SomeController::class;
                $action = 'myAction';
            }
    
            $container = app();
            $route = $container->make(Route::class);
            $controllerInstance = $container->make($controller);
    
            return (new ControllerDispatcher($container))->dispatch($route, $controllerInstance, $action);
        }
    }
    

    Hope this helps!

提交回复
热议问题