创建可以访问我的模型的Laravel 5.1中间件

时间:2015-08-07 00:30:34

标签: php laravel laravel-4 laravel-5 laravel-5.1

在Laravel 4.2中,我有以下过滤器,阻止一个用户查看/编辑/删除不同用户的课程,这是一个基于"课程"模型。这是我正在使用的代码:

Route::filter('restrictPermission', function($route)
{
    $id = $route->parameter('id');
    $course = Course::find($id);
    $user_id = $course->user_id;
    if(Auth::user()->id !== $user_id)
        return Redirect::to('/')->with('flash_message', '*** Permission denied ***');
    # This compares the currently logged in user's id to the course's
    # user ID (in the database) so that the logged in user can 
    # only view or delete their own courses.
});

以下是我尝试创建的中间件,它与上面的过滤器完全相同:

<?php
namespace App\Http\Middleware;
use Closure;

class RedirectIfWrongUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $id = $route->parameter('id');
        $course = Course::find($id);
        $user_id = $course->user_id;
        if ($request->user()->id !== $user_id) {
            return Redirect::to('/')->with('flash_message', '*** Permission denied ***');
        }

        return $next($request);
    }
}

问题在于我不知道如何让中间件识别课程类和课程::功能。

任何建设性的帮助都会受到最高的赞赏。

1 个答案:

答案 0 :(得分:9)

I thought it is very straight forward with DI mechanism in place already.

<?php
    namespace App\Http\Middleware;
    use Closure;
    use App\Course;


    class RedirectIfWrongUser
    {
        protected $course;

        public function __construct(Course $course) {
            $this->course = $course;
        }
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            // normally I do this, this will get the id for routes /user/{id}

            $id = $request->id;

            // if you want the actual route, do this
            // $route = $request->route();

            $course = $this->course->find($id);
            $user_id = $course->user_id;
            if ($request->user()->id !== $user_id) {
                // better use shorthand
                return redirect()->to('/')->with('flash_message', '*** Permission denied ***');
            }

            return $next($request);
        }
    }