Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

php - Laravel Creating Dynamic Routes to controllers from Mysql database

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');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...