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

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

问题描述

我有下表:mysql数据库中的group_pages,页面名称为route name:

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天全站免登陆