Laravel Creating Dynamic Routes to controllers from Mysql database

后端 未结 5 640
无人及你
无人及你 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 11:51

    This is not the right way to create dynamic pages instead, you should use a database and keep all pages in the database. For example:

    // Create pages table for dynamic pages
    id | slug | title | page_content 
    

    Then create Page Eloquent model:

    class Page extends Eloquent {
        // ...
    }
    

    Then create Controller for CRUD, you may use a resource controller or a normal controller, for example, normally a PageController:

    class PageController extends BaseController {
    
        // Add methods to add, edit, delete and show pages
    
        // create method to create new pages
        // submit the form to this method
        public function create()
        {
            $inputs = Input::all();
            $page = Page::create(array(...));
        }
    
        // Show a page by slug
        public function show($slug = 'home')
        {
            $page = page::whereSlug($slug)->first();
            return View::make('pages.index')->with('page', $page);
        }
    }
    

    The views/page/index.blade.php view file:

    @extends('layouts.master')
    {{-- Add other parts, i.e. menu --}}
    @section('content')
        {{ $page->page_content }}
    @stop
    

    To show pages create a route like this:

    // could be page/{slug} or only slug
    Route::get('/{slug}', array('as' => 'page.show', 'uses' => 'PageController@show'));
    

    To access a page, you may require url/link like this:

    http://example.com/home
    http://example.com/about
    

    This is a rough idea, try to implement something like this.

    0 讨论(0)
  • 2020-12-07 11:58

    We can make dynamic route by this way

    // Instanciate a router class.
    $router = app()->make('router');
    

    Get Route value from Database

    // For route path this can come from your database.
    $paths = ['path_one','path_two','path_three'];
    

    Then iterate the value to make dynamic route

    // Then iterate the router "get" method.
    foreach($paths as $path){
        $router->resource($path, 'YourController');
    }
    

    You can use GET|POST|PUT|PATCH|DELETE methods also

    // Then iterate the router "get" method.
    foreach($paths as $path){
        $router->get($path, 'YourController@index')->name('yours.index');
    }
    
    0 讨论(0)
  • 2020-12-07 12:03

    try

    Route::get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
    
    $pages = 
    Cache::remember('pages', 5, function() {
        return DB::table('pages')
                ->where('status', 1)
                ->lists('slug');
    
    });
    
    if(!empty($pages)) 
    {
      foreach ($pages as $page)
      {
        Route::get('/{'.$page.'}', ['as' => $page, 'uses' => 'PagesController@show']);
       }
    }
    
    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-12-07 12:10

    There is a component available, which you can use to store routes in a database. As an extra advantage, this component only loads the current active route, so it improves performance, since not all routes are loaded into the memory.

    https://github.com/douma/laravel-database-routes

    Follow the installation instructions provided in the readme.

    Storing routes in the database

    The only thing needed here is injecting the RouteManager into for example a cli command. With addRoute can tell the RouteManager to store the route into the database. You can easily change this code and use your own repository of pages or other data to construct the routes.

    use Douma\Routes\Contracts\RouteManager;
    
    class RoutesGenerateCommand extends Command 
    {
        protected $signature = 'routes:generate';
        private $routeManager;
    
        public function __construct(RouteManager $routeManager)
        {
            $this->routeManager = $routeManager;
        }
    
        public function handle()
        {
            $this->routeManager->addRoute(
                new Route('/my-route', false, 'myroute', MyController::class, 'index')
            );
        }
    }
    

    Run this cli command every 2-5 minutes or after a change in your data to make sure the routes are recent.

    Register the RouteMiddleware in App\Http\Kernel.php

    \Douma\Routes\Middleware\RouteMiddleware::class

    Empty your web.php

    If you have defined any Laravel route, make sure to empty this file.

    Using routes from the database

    You can use the route in blade:

    {{ RouteManager::routeByName('myroute')->url() }}
    

    Or you can inject the RouteManager-interface anywhere you like to obtain the route:

    use Douma\Routes\Contracts\RouteManager;
    class MyClass
    {
        public function __construct(RouteManager $routeManager) 
        {
            $this->routeManager = $routeManager;
        }
    
        public function index()
        {
            echo $this->routeManager->routeByName('myroute')->url();
        }
    }
    

    For more information see the readme.

    0 讨论(0)
提交回复
热议问题