路由基本有三种
Route::get('order/{id}',['as'=>'order.detail','uses'=>'OrderController@show']);
Route::controller('preview', 'PreviewController');
Route::resource('badmin', 'BadminController');
基本想法是搭建一个FormController,所有以后需要配置生成后台的controller就继承这个FormController就好了。在FormController中定义属性:
class FormController extends BaseController {
// 对应的模型
protected $model;
// 所有的字段
protected $fields_all;
// 列表页显示的字段
protected $fields_show;
// 编辑页面显示的字段
protected $fields_edit;
// 创建页面显示的字段
protected $fields_create;
}
在git使用命令php artisan make:controller Admin/RoleController –resource 如果不加–resource空控制器。加–resource 会创建控制器 增删改查
在构造函数中把一些诸如Input,全局定义的东西都share到模版中
public function __construct()
{
// TODO:做一些基础的判断,如果没有的话就抛出异常
$route = Route::currentRouteAction();
list($this->controller, $action) = explode('@', $route);
View::share('controller', $this->controller);
$fields_show = array();
foreach ($this->fields_show as $field) {
$fields_show[$field] = $this->fields_all[$field];
}
View::share('fields_show', $fields_show);
$fields_edit = array();
foreach ($this->fields_edit as $field) {
$fields_edit[$field] = $this->fields_all[$field];
}
View::share('fields_edit', $fields_edit);
$fields_create = array();
foreach ($this->fields_create as $field) {
$fields_create[$field] = $this->fields_all[$field];
}
View::share('fields_create', $fields_create);
View::share('input', Input::all());
}
把controller放到外面是为了在view中可以使用诸如:
action(controller.′@destroy′,controller.′@destroy′,model->id), 的路径定义
public function index()
{
$model = new $this->model;
$builder = $model->orderBy('id', 'desc');
$input = Input::all();
foreach ($input as $field => $value) {
if (empty($value)) {
continue;
}
if (!isset($this->fields_all[$field])) {
continue;
}
$search = $this->fields_all[$field];
$builder->whereRaw($search['search'], [$value]);
}
$models = $builder->paginate(20);
return View::make('form.index', [
'models' => $models,
]);
}
create函数:
public function create()
{
return View::make('form.create', []);
}
store函数:
public function store()
{
$model = new $this->model;
$model->fill(Input::all());
$model->save();
return Redirect::to(action($this->controller . '@index'));
}
edit,update,destory函数
public function edit($id)
{
$model = new $this->model;
$model = $model->find($id);
return View::make('form.edit', compact('model'));
}
public function update($id)
{
$model = new $this->model;
$model = $model->find($id);
$model->fill(Input::all());
$model->save();
return Redirect::to(action($this->controller . '@index'));
}
public function destroy($id)
{
$model = new $this->model;
$model->destroy($id);
return Redirect::to(action($this->controller . '@index'));
}