Laravel Creating Dynamic Routes to controllers from Mysql database
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']);
}
}
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.
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!