user3089840 user3089840 - 1 month ago 6
PHP Question

Creating a Laravel 5.1 Middleware that can access my Model

In Laravel 4.2 I had the following filter that prevented one user from viewing/editing/deleting a different user's course, which is an object based off of a "Course" model. Here is the code I was using:

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


Here is the Middleware I am trying to create that does the same thing as the above filter:

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


The problem is that I don't know how to get the Middleware to recognize the Course class and the Course:: functionality.

Any constructive help would be most appreciated.

Answer

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