Laravel Creating Dynamic Routes to controllers from Mysql database

后端 未结 5 641
无人及你
无人及你 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.

提交回复
热议问题