I have the following table: group_pages in mysql database with page name route name :
id name route
--------------------
0 About about
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.