title: Laravel Middleware return variable to controller
body: <p>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.</p>
  
  <p>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. </p>
  
  <p>Here is an example of the setup;</p>
  
  <p>-- routes.php</p>
  
  <pre><code>Route::get('pages/{id}', [
     'as' =&gt; 'pages',
     'middleware' =&gt; 'pageUser'
     'uses' =&gt; 'PagesController@view'
  ]);
  </code></pre>
  
  <p>-- PageUserMiddleware.php (class PageUserMiddleware)</p>
  
  <pre><code>public function handle($request, Closure $next)
      {
          //get the page
          $pageId = $request-&gt;route('id');
          //find the page with users
          $page = Page::with('users')-&gt;where('id', $pageId)-&gt;first();
          //check if the logged in user exists for the page
          if(!$page-&gt;users()-&gt;wherePivot('user_id', Auth::user()-&gt;id)-&gt;exists()) {
              //redirect them if they don't exist
              return redirect()-&gt;route('redirectRoute');
          }
          return $next($request);
      }
  </code></pre>
  
  <p>-- PagesController.php</p>
  
  <pre><code>public function view($id)
  {
      $page = Page::with('users')-&gt;where('id', $id)-&gt;first();
      return view('pages.view', ['page' =&gt; $page]);
  }
  </code></pre>
  
  <p>As you can see, the <code>Page::with('users')-&gt;where('id', $id)-&gt;first()</code> 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. </p>