使用RESTful控制器时将路由参数传递给过滤器

时间:2014-03-23 09:55:51

标签: laravel routing

我已经搜索了很长时间,但没有什么能适合我的问题。 我在我的网站上使用RESTful控制器。对于某些控制器操作,需要一些过滤器,我会这样做(我在构造函数中使用beforeFilter()函数):

<?php
    class PostController extends BaseController {

        public function __construct()
        {
            $this->beforeFilter('auth',array('only'=>array('getCreate','postCreate','getEdit','postEdit','postAddComment')));
            $this->beforeFilter('csrf',array('only'=>array('postCreate','postEdit')));
        //  $this->beforeFilter('auth_post_edit', array('only'=>array('postEdit','getEdit')));
        }

        public function getIndex
        {

            $posts = Post::all();
            return View::make('home')->with('posts',$posts);
        }

        public function getCreate()
        {
            return View::make('posts.create');
        }
...

对于评论过滤器,它是为了确保只有帖子的作者可以编辑帖子,所以我需要将作为URI参数传递的post_id传递给过滤器(或从过滤器访问它)。 一些链接显示我如何使用过滤器中的$route->getParameter('param')从过滤器访问参数,但问题是因为我甚至没有命名我的参数(它们在控制器操作中命名),我无法使用上述方法从过滤器访问它们。 那么,我如何从过滤器中访问路由参数,或者/我如何在RESTful控制器中命名路由参数(而不是在他们的操作中)?

1 个答案:

答案 0 :(得分:1)

您可以在过滤器中使用Request :: segment()

 Route::filter('foo', function()
{
    $param=Request::segment(2); //if the parameter is on the 2nd uri fregment.
    $post=Post::find($param);
    if ($post->author_id != Auth::user()->id)
    {
        return App::abort('404'); //or whatever
    }
});
相关问题