Laravel Creating Dynamic Routes to controllers from Mysql database

烂漫一生 提交于 2019-12-17 17:25:51

问题


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

   id   name      route
  --------------------
    0   About      about
    1   Contact    contact
    2   Blog       blog

what I am trying to do is to create dynamic routes in my : routes.php ?

Where if I go to for example: /about it will go to AboutController.php ( which will be created dynamically) is that possible? is it possible to create a dynamic controller file?

I am trying to create dynamic pages routes that links to a controller

example i want to generate this dynamically in my routes.php

Route::controller('about', 'AboutController');

Route::controller('contact', 'ContactController');

Route::controller('blog', 'BlogController');

回答1:


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.




回答2:


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!




回答3:


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']);
   }
}



回答4:


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.



来源:https://stackoverflow.com/questions/23145245/laravel-creating-dynamic-routes-to-controllers-from-mysql-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!