【问题标题】:Passing Route Parameters to Filters when Using RESTful Controllers使用 RESTful 控制器时将路由参数传递给过滤器
【发布时间】:2014-03-25 19:28:19
【问题描述】:

我已经搜索了很长时间,但没有什么能完全符合我的问题。 我在我的网站上使用 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-&gt;getParameter('param') 从过滤器访问参数,但问题是因为我什至没有命名我的参数(它们在控制器操作中命名),我无法访问它们使用上述方法从过滤器中提取。 那么,我如何从过滤器中访问路由参数,或/以及如何在 RESTful 控制器中命名路由参数(而不是在它们的操作中)?

【问题讨论】:

  • 您也可以尝试在过滤器中使用 Input::get('album_id') (或您拥有的任何参数)。
  • @DimitrisKontoulis,但我认为Input::get() 用于处理来自表单的输入? (它不工作)。我刚刚不得不搁置 RESTful 控制器的想法,并决定只做 routes.php 的所有事情
  • 或者你可以使用 Request::segment() 方法。它在 Illuminate\Http\Request 类中。

标签: laravel routing


【解决方案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
    }
});

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 1970-01-01
    • 2016-05-16
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-03
    相关资源
    最近更新 更多