I am carrying out a permissions check on a user to determine whether they can view a page or not. This involves passing the request through some middleware first.
The problem I have is I am duplicating the same database query in the middleware and in the controller before returning the data to the view itself.
Here is an example of the setup;
-- routes.php
Route::get('pages/{id}', [
   'as' => 'pages',
   'middleware' => 'pageUser'
   'uses' => 'PagesController@view'
]);
-- PageUserMiddleware.php (class PageUserMiddleware)
public function handle($request, Closure $next)
    {
        //get the page
        $pageId = $request->route('id');
        //find the page with users
        $page = Page::with('users')->where('id', $pageId)->first();
        //check if the logged in user exists for the page
        if(!$page->users()->wherePivot('user_id', Auth::user()->id)->exists()) {
            //redirect them if they don't exist
            return redirect()->route('redirectRoute');
        }
        return $next($request);
    }
-- PagesController.php
public function view($id)
{
    $page = Page::with('users')->where('id', $id)->first();
    return view('pages.view', ['page' => $page]);
}
As you can see, the Page::with('users')->where('id', $id)->first() is repeated in both the middleware and controller. I need to pass the data through from one to the other so an not to duplicate. 
 
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
    