Laravel 从 Mysql 数据库创建到控制器的动态路由 [英] Laravel Creating Dynamic Routes to controllers from Mysql database

查看:19
本文介绍了Laravel 从 Mysql 数据库创建到控制器的动态路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表:mysql 数据库中的 group_pages 页面名称路由名称:

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

我要做的是在我的 : routes.php 中创建动态路由?

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

如果我去哪里,例如: /about 它将去 AboutController.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

示例我想在我的 routes.php

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

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

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

推荐答案

这不是创建动态页面的正确方法,您应该使用数据库并将所有页面保留在数据库中.例如:

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 

然后创建Page Eloquent模型:

class Page extends Eloquent {
    // ...
}

然后为CRUD创建Controller,你可以使用resource控制器或普通控制器,例如通常是PageController:

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

views/page/index.blade.php 视图文件:

@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'));

要访问一个页面,您可能需要像这样的 url/link:

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.

这篇关于Laravel 从 Mysql 数据库创建到控制器的动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆