umefarooq 的回答是正确的,但希望这个回答能让您更深入地了解如何在 Laravel 开发中抢占先机,并获得一致的最佳实践编程风格。
首先,类名应该以大写字母开头。尽量保持方法/函数名以小写字母开头,类名以大写字母开头。
其次,您不需要 BaseController 前面的\。如果您对控制器进行名称间距,则只需要反斜杠。例如如果您的控制器位于文件夹 Admin\TestController.php 中,并且您通过在文件开头键入 <?php namespace Admin 将您的 TestController 放在 Admin 命名空间中。这是您应该使用\BaseController 的时候,因为您告诉您的TestController 从全局命名空间扩展BaseController。或者,在你声明你的类之前,你可以输入use BaseController;,你不需要每次都输入\。
与您的问题特别相关:
当你在你的路由文件中使用资源路由时,你是在告诉 Laravel 控制器可以有以下任何或所有方法:index、show、create、store、edit、 update 和 destroy。
因此,Route::resource('test', 'TestController'); 将指向控制器文件夹中的 TestController.php。
您的 TestController 的结构应如下所示,大多数 restful 控制器将使用以下作为某种样板:
<?php
class TestController extends BaseController
{
public function __construct()
{
}
// Typically used for listing all or filtered subset of items
public function index()
{
$tests = Test::all();
return View::make('test.index', compact('tests'));
}
// Typically shows a specific item detail
public function show($id)
{
$test = Test::find($id);
return View::make('test.show', compact('test'));
}
// Typically used to show the form which creates a new resource.
public function create()
{
return View::make('test.create');
}
// Handles the post request from the create form
public function store()
{
$test = new Test;
$test->attribute1 = Input::get('attribute1');
$test->attribute2 = Input::get('attribute2');
$test->attribute3 = Input::get('attribute3');
$test->attribute4 = Input::get('attribute4');
if ($test->save())
{
return Redirect::route('test.show', $test->id);
}
}
// Shows the edit form
public function edit($id)
{
$test = Test::find($id);
return View::make('test.edit', compact('test'));
}
// Handles storing the submitted PUT request from the edit form.
public function update($id)
{
$test = Test::find($id);
$test->attribute1 = Input::get('attribute1');
$test->attribute2 = Input::get('attribute2');
$test->attribute3 = Input::get('attribute3');
$test->attribute4 = Input::get('attribute4');
if ($test->save())
{
return Redirect::route('test.show', [$id]);
}
}
// Used to delete a resource.
public function destroy($id)
{
$test = Test::find($id);
$test->delete();
return Redirect::route('test.index');
}
}
此外,使用资源控制器的好处在于您可以利用命名路由。
在终端窗口中,输入php artisan routes。
您应该会看到 7 条命名路线。
test.index
test.destroy
test.show
test.edit
test.destroy
test.create
test.update
所以在你的表单中,而不是做
{{ Form::open(array('url'=>'test/loginform')) }} 你可以将 url 指向一个命名路由:
{{ Form::open(array('route' => array('test.store')) }}
这样,如果您更改了 url,或者需要在站点结构中移动,这将很容易,因为表单发布 url 将自动绑定到路由文件中的命名路由。您无需更新每一个视图以确保 url 指向正确的位置。
最后,作为起点,我建议使用 JefreyWay/Laravel-4-Generators 包。 https://github.com/JeffreyWay/Laravel-4-Generators 。使用它们来创建您的资源、控制器、视图等,并查看生成器如何为您构建模型、视图和控制器。
这里是另一个帮助您入门的资源:
https://laracasts.com/lessons/understanding-rest