Laravel Controllers

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}‘, ‘[email protected]‘);

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\[email protected]‘);

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‘ => ‘[email protected]‘,
                                        ‘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(‘[email protected]‘);

$url = action(‘[email protected]‘);

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‘ => ‘[email protected]‘));

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.

时间: 2024-10-12 19:49:50

Laravel Controllers的相关文章

laravel 在controllers中添加子文件夹和控制器出错解决办法

首先我们在controllers文件夹中建立一个admin文件夹. 第一种方法:直接在后台建立控制器,比如AdminController.php 里面正常的写上我们的内容. 在路由表中, Route::get('admin','[email protected]'); 我们发现程序报错,说无法找到控制器AdminController. 我们打开命令行工具,进入到该项目的更目录中,也就是artisan,composer.json所在的目录中, 运行命令 composer dumpautoload

Laravel 5.4 中的异常处理器和HTTP异常处理实例教程

错误和异常是处理程序开发中不可回避的议题,在本地开发中我们往往希望能捕获程序抛出的异常并将其显示打印出来,以便直观的知道程序在哪里出了问题并予以解决,而在线上环境我们不希望将程序错误或异常显示在浏览器中(出于安全考虑),这个时候我们仍然要捕获异常,只不过不是显示到浏览器中,而是记录到日志中,方便日后排查问题. 百牛信息技术bainiu.ltd整理发布于博客园 Laravel当然支持PHP原生的错误和异常处理,但是在此基础上进行了一些封装处理,从而更方便在不同开发环境切换以及对错误和异常的处理.

Laravel之控制器

一.简介 将所有的请求处理逻辑都放在单个routes.php 中肯定是不合理的,你也许还希望使用控制器类组织管理这些行为.控制器可以将相关的 HTTP 请求封装到一个类中进行处理.通常控制器存放在app/Http/Controllers 目录中. 二.基本控制器 1.简单示例下面是一个基本控制器类的例子.所有的 Laravel 控制器应该继承自 Laravel 自带的控制器基类Controller <?php namespace App\Http\Controllers; use App\Use

laravel框架常用目录路径

app_path() app_path函数返回app目录的绝对路径:$path = app_path(); 你还可以使用app_path函数为相对于app目录的给定文件生成绝对路径:$path = app_path('Http/Controllers/Controller.php'); base_path() base_path函数返回项目根目录的绝对路径:$path = base_path(); 你还可以使用base_path函数为相对于应用目录的给定文件生成绝对路径:$path = base

Laravel 使用多个数据库的问题。

这几天在使用Laravel 开发一个系统.这个系统连2个数据库.一个名为blog,一个名为center. center 数据库的作用是作为用户中心.可能会有其他几个系统相连,属于公用数据库.主要是用来用户登录认证. blog 数据库的作用是放文章,不会牵扯到认证方面. 我的想法是使用center数据库作为用户的登录认证,登录以后在发文章切换到blog数据库. 目前我的.env配置如下 DB_HOST=localhost DB_DATABASE=blog DB_DATABASE_CENTER=ce

Laravel 5系列教程四:数据库和Eloquent

免费视频教程地址https://laravist.com/series/laravel-5-basic 上一篇写了一些Laravel Blade的基本用法和给视图传递变量的几种方式, 这一节我们来说说跟数据库打交道的数据库配置和Laravel强大的Eloquent. Laravel的数据库配置 本部分内容为下节做准备 Laravel的配置文件都是在项目目录的config/文件夹之下,这里也就是在blog/config文件夹之下,你可以打开这个文件夹看看,你面有很多配置文件:如mail.php(配

Laravel 5系列教程二:路由,视图,控制器工作流程

免费视频教程地址https://laravist.com/series/laravel-5-basic 上一篇教程我们走了那么长的路,终于把Laravel安装好了,这一篇教程我们就要进入Laravel的神奇世界了,主要是讲解Laravel的Router,Views,Controllers的工作流程,目的也就是让大家明白Laravel在处理一个get请求的时候是如何工作的. 在开始之前,我们首先得将我们的服务器启动起来,如果你使用Laravel的artisan,你可以直接: php artisan

Laravel 5 系列教程三:视图变量传递和Blade

免费视频教程地址https://laravist.com/series/laravel-5-basic 上一篇我们简单地说了Router,Views和Controllers的工作流程,这一次我就按照上一篇的计划,来说说下面几个内容: 向视图中传递变量 Blade模板的用法 向视图中传递变量 我们在开发web应用当中,通常都不是为了写静态页面而生的,我们需要跟数据打交道,那么这个时候,问题就来了,在一个MVC的框架中,怎么将数据传给视图呢?比如我们要在 ArticleController 的 in

laravel队列-让守护进程处理耗时任务

待解决的问题 最近在做一个服务器集群管理的web项目,需要处理一些极其耗时的操作,比如磁盘格式化分区.对于这个需求,最开始的想法是,为了让节点上的rpc(远程过程调用) service端尽可能简单(简单到只需要popen执行一条指令即可,有时间我再专门写一篇博客讲讲这个项目的rpc是如何实现的),我们选择了让web端直接等待处理结果,那么问题来了,如何保证用户不必等待,又能保证任务准确的执行呢? 简单的rpc结构如下图 以往在处理一些稍微耗时的操作,可以通过优化代码结构,优化数据库操作次数,起一