Basic Controllers

Instead of defining all of your route-level logic in a single routes.php file, you may wish to organize this behavior using Controller classes. Controllers can group related route logic into a class, as well as take advantage of more advanced framework features such as automatic dependency injection.

Controllers are typically stored in the app/controllers directory, and this directory is registered in the classmap option of your composer.json file by default. However, controllers can technically live in any directory or any sub-directory. Route declarations are not dependent on the location of the controller class file on disk. So, as long as Composer knows how to autoload the controller class, it may be placed anywhere you wish.

Here is an example of a basic controller class:

class UserController extends BaseController {

    /**
* Show the profile for the given user.
*/
public function showProfile($id)
{
$user = User::find($id); return View::make('user.profile', array('user' => $user));
} }

All controllers should extend the BaseController class. The BaseController is also stored in the app/controllers directory, and may be used as a place to put shared controller logic. The BaseController extends the framework's Controller class. Now, we can route to this controller action like so:

Route::get('user/{id}', 'UserController@showProfile');

If you choose to nest or organize your controller using PHP namespaces, simply use the fully qualified class name when defining the route:

Route::get('foo', 'Namespace\FooController@method');

Note: Since we're using Composer to auto-load our PHP classes, controllers may live anywhere on the file system, as long as composer knows how to load them. The controller directory does not enforce any folder structure for your application. Routing to controllers is entirely de-coupled from the file system.

You may also specify names on controller routes:

Route::get('foo', array('uses' => 'FooController@method',
'as' => 'name'));

To generate a URL to a controller action, you may use the URL::action method or the action helper method:

$url = URL::action('FooController@method');

$url = action('FooController@method');

You may access the name of the controller action being run using the currentRouteAction method:

$action = Route::currentRouteAction();

Controller Filters

Filters may be specified on controller routes similar to "regular" routes:

Route::get('profile', array('before' => 'auth',
'uses' => 'UserController@showProfile'));

However, you may also specify filters from within your controller:

class UserController extends BaseController {

    /**
* Instantiate a new UserController instance.
*/
public function __construct()
{
$this->beforeFilter('auth', array('except' => 'getLogin')); $this->beforeFilter('csrf', array('on' => 'post')); $this->afterFilter('log', array('only' =>
array('fooAction', 'barAction')));
} }

You may also specify controller filters inline using a Closure:

class UserController extends BaseController {

    /**
* Instantiate a new UserController instance.
*/
public function __construct()
{
$this->beforeFilter(function()
{
//
});
} }

If you would like to use another method on the controller as a filter, you may use @ syntax to define the filter:

class UserController extends BaseController {

    /**
* Instantiate a new UserController instance.
*/
public function __construct()
{
$this->beforeFilter('@filterRequests');
} /**
* Filter the incoming requests.
*/
public function filterRequests($route, $request)
{
//
} }

Implicit Controllers

Laravel allows you to easily define a single route to handle every action in a controller. First, define the route using the Route::controller method:

Route::controller('users', 'UserController');

The controller method accepts two arguments. The first is the base URI the controller handles, while the second is the class name of the controller. Next, just add methods to your controller, prefixed with the HTTP verb they respond to:

class UserController extends BaseController {

    public function getIndex()
{
//
} public function postProfile()
{
//
} public function anyLogin()
{
//
} }

The index methods will respond to the root URI handled by the controller, which, in this case, is users.

If your controller action contains multiple words, you may access the action using "dash" syntax in the URI. For example, the following controller action on our UserController would respond to the users/admin-profile URI:

public function getAdminProfile() {}

RESTful Resource Controllers

Resource controllers make it easier to build RESTful controllers around resources. For example, you may wish to create a controller that manages "photos" stored by your application. Using the controller:makecommand via the Artisan CLI and the Route::resource method, we can quickly create such a controller.

To create the controller via the command line, execute the following command:

php artisan controller:make PhotoController

Now we can register a resourceful route to the controller:

Route::resource('photo', 'PhotoController');

This single route declaration creates multiple routes to handle a variety of RESTful actions on the photo resource. Likewise, the generated controller will already have stubbed methods for each of these actions with notes informing you which URIs and verbs they handle.

Actions Handled By Resource Controller

Verb Path Action Route Name
GET /resource index resource.index
GET /resource/create create resource.create
POST /resource store resource.store
GET /resource/{resource} show resource.show
GET /resource/{resource}/edit edit resource.edit
PUT/PATCH /resource/{resource} update resource.update
DELETE /resource/{resource} destroy resource.destroy

Sometimes you may only need to handle a subset of the resource actions:

php artisan controller:make PhotoController --only=index,show

php artisan controller:make PhotoController --except=index

And, you may also specify a subset of actions to handle on the route:

Route::resource('photo', 'PhotoController',
array('only' => array('index', 'show'))); Route::resource('photo', 'PhotoController',
array('except' => array('create', 'store', 'update', 'destroy')));

By default, all resource controller actions have a route name; however, you can override these names by passing a names array with your options:

Route::resource('photo', 'PhotoController',
array('names' => array('create' => 'photo.build')));

Handling Nested Resource Controllers

To "nest" resource controllers, use "dot" notation in your route declaration:

Route::resource('photos.comments', 'PhotoCommentController');

This route will register a "nested" resource that may be accessed with URLs like the following:photos/{photoResource}/comments/{commentResource}.

class PhotoCommentController extends BaseController {

    public function show($photoId, $commentId)
{
//
} }

Adding Additional Routes To Resource Controllers

If it becomes necessary for you to add additional routes to a resource controller beyond the default resource routes, you should define those routes before your call to Route::resource:

Route::get('photos/popular');
Route::resource('photos', 'PhotoController');

Handling Missing Methods

When using Route::controller, a catch-all method may be defined which will be called when no other matching method is found on a given controller. The method should be named missingMethod, and receives the method and parameter array for the request:

Defining A Catch-All Method

public function missingMethod($parameters = array())
{
//
}

If you are using resource controllers, you should define a __call magic method on the controller to handle any missing methods.

Laravel Controllers的更多相关文章

  1. Laravel 5.2 错误-----ReflectionException in compiled.php line 8572: Class App\Http\Controllers\Apih5\ZhaoshangController does not exist

    测试的时候,报错了!想不到找了半天的问题,居然是个低级错误. <?php namespace App\Http\Controllers\Apih5; use Illuminate\Http\Re ...

  2. laravel :Call to undefined function App\Http\Controllers\success() 解决方法

    今天在调用方法时,报错如下:Call to undefined function App\Http\Controllers\success():方法已定义好了,所以我怀疑是未引入function.ph ...

  3. Laravel大型项目系列教程(三)之发表文章

    Laravel大型项目系列教程(三)之发表文章 一.前言 上一节教程中完成了用户管理,这节教程将大概完成发表Markdown格式文章并展示的功能. 二.Let's go 1.数据库迁移 文章模块中我们 ...

  4. laravel强大功能路由初探(二)

    目标当然是先输出helloworld 配置hosts文件和apache下的httpd-vhosts.conf, hosts:127.0.0.1  www.blog.com httpd-vhosts.c ...

  5. laravel 生成验证码的方法

    在Laravel中有很多图片验证码的库可以使用,本篇介绍其中之一:gregwar/captcha,这个库比较简单,在Laravel中比较常用.下面我们就来介绍下使用细节: 首先, composer.j ...

  6. Laravel 数据库读写分离

    config/database.php ... 'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localho ...

  7. 关于laravel基础知识

    laravel任务管理知识点 1.配置数据库环境 首先要找到congif/app.php,在这里会发现一些全局的系统设置,包括语言,时区等. 重要的是会发现前几个数组都使用了env()这个函数,这个时 ...

  8. [PHP] - Laravel - 用户登陆中间件

    前言 Laravel 4中,可以使用Route::filter,而在Laravel 5中,没有了filter.php文件,官方建议使用中间件做. 下面是用户登陆的测试例子,涉及到的一些方法和使用,先参 ...

  9. [PHP] - Laravel - 列表、新增、修改、删除例子

    前言 Laravel默认是自带了CURD的功能,使用路由的Route::resource可以做到. 但真正的项目中,这往往不是我们所需要的.因为一个项目会有比较复杂的计算.验证等功能. 下面是对项目中 ...

随机推荐

  1. WIN7建立网络映射磁盘

    建立网络映射磁盘 如果需要经常访问网络中的同一个共享文件夹,则可以将这个共享文件夹直接映射为本地计算机中的一个虚拟驱动器.其具体操作如下. (1)双击桌面上"计算机"图标,打开&q ...

  2. git中手动删除的文件如何在git中删除

    在日常开发中,我们可能或手动删除(delete键删除的)一些文件,然而我们本来应该是用git rm fileName命令删除的,但是现在我们手动删除了,那么要如何在git里面讲那些手动删除的文件删除呢 ...

  3. [58 Argo]让argo跑起来

    接上一章,使用命令mvn jetty:run启动Argo,进入localhost的页面: 58在这里给了几种常见的访问和传值方法的示例,当点击到第三条<区分queryString和form参数& ...

  4. poj 3277 City Horizon (线段树 扫描线 矩形面积并)

    题目链接 题意: 给一些矩形,给出长和高,其中长是用区间的形式给出的,有些区间有重叠,最后求所有矩形的面积. 分析: 给的区间的范围很大,所以需要离散化,还需要把y坐标去重,不过我试了一下不去重 也不 ...

  5. django - 修改 request.POST的值

    # querydict改为mutable data = data.copy() data.update({'key_list': DATA_UPLOAD_PARAMETER}) 默认的request. ...

  6. 【转】让apache支持中文路径或者中文文件

    本帖最后由 狂人阿川 于 2013-4-12 19:13 编辑 今天在给一美国VPS客户调试他的程序的时候.发现他的网站有中文名称.貌似apache无法认识中文路径,火狐下面能下载他的文件,IE下面不 ...

  7. 新浪使用Redis

    新浪微博的工程师们曾经在多个公开场合都讲到过,微博平台当前在使用并维护着可能是世界上最大的Redis集群,其中最大的一个业务,单个业务使用了超过 10T 的内存,这里说的就是微博关系服务. 风起 20 ...

  8. ashx-auth-黑色简洁验证码

    ylbtech-util: ashx-auth-黑色简洁验证码 ashx-auth-黑色简洁验证码 1.A,效果图返回顶部   1.B,源代码返回顶部 /ImageUniqueCode.ashx &l ...

  9. [Tommas] 测试用例覆盖率(三)

    三.测试数据的设计 每一个测试思路最终都要转化成具体的数据才能来执行.关于测试数据设计的方法也不外乎那几种,就不再赘述了.此处单就一些经常易犯的错误,提出一些注意点,作为用例数据设计时的参考: 1.尽 ...

  10. linux常用命令之--文本编辑和文本内容查看命令

    linux的文本编辑和文本内容查看命令 1.文本编辑命令 vi:用于编辑文本文件,基本上可以分为三种模式,分别是一般模式.编辑模式.命令行模式. 一般模式:当编辑一个文件时,刚进入文件就是一般模式. ...