Laravel 4中身份验证前路由资源集不起作用

8
我在routes.php中添加了这个代码,期望它可以检查页面的身份验证会话,但是它似乎没有起作用。
Route::resource('ticket', 'TicketController', array('before' => 'auth') );

我转到控制器,采用另一种方式工作。它有效。

class TicketController extends BaseController {

public function __construct()
{
    $this->beforeFilter('auth');
}

请问在哪里可以获取更多关于Route::resource()的文档?它能接受什么类型的参数?

1个回答

22

好的...我找到了答案。

\vendor\laravel\framework\src\Illuminate\Routing\Router.php

public function resource($resource, $controller, array $options = array())
    {
        // If the resource name contains a slash, we will assume the developer wishes to
        // register these resource routes with a prefix so we will set that up out of
        // the box so they don't have to mess with it. Otherwise, we will continue.
        if (str_contains($resource, '/'))
        {
            $this->prefixedResource($resource, $controller, $options);

            return;
        }

        // We need to extract the base resource from the resource name. Nested resources
        // are supported in the framework, but we need to know what name to use for a
        // place-holder on the route wildcards, which should be the base resources.
        $base = $this->getBaseResource($resource);

        $defaults = $this->resourceDefaults;

        foreach ($this->getResourceMethods($defaults, $options) as $method)
        {
            $this->{'addResource'.ucfirst($method)}($resource, $base, $controller);
        }
    }

protected function getResourceMethods($defaults, $options)
    {
        if (isset($options['only']))
        {
            return array_intersect($defaults, $options['only']);
        }
        elseif (isset($options['except']))
        {
            return array_diff($defaults, $options['except']);
        }

        return $defaults;
    }

如您所见,它仅接受onlyexcept参数。

如果您想在route.php中实现相同的结果,可以按以下方式完成:

Route::group(array('before'=>'auth'), function() {   
    Route::resource('ticket', 'TicketController');
});

或者您可以使用控制器的beforeFilter()方法。$this->beforeFilter('auth', ['except' => 'destroy']);。请查看Devon在此链接中的评论:https://laracasts.com/index.php/discuss/channels/general-discussion/how-can-i-declare-a-before-filter-on-a-routeresource - Alwin Kesler

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接