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

Creating a Laravel 5.1 Middleware that can access my Model

在 Laravel 4.2 中,我有以下过滤器阻止一个用户 viewing/editing/deleting 另一个用户的课程,这是一个基于 "Course" 模型的对象。这是我使用的代码:

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);
    }
}

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

非常感谢任何建设性的帮助。

我认为已经有了 DI 机制是非常简单的。

<?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);
        }
    }