I am performing a user rights check to determine if they can view the page or not. This includes transmitting the request through some middleware.
The problem is that I duplicate the same database query in the middleware and in the controller before returning the data to the view itself.
Here is an example 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, Page::with('users')->where('id', $id)->first() repeated both in the middleware and in the controller. I need to transfer data from one to another so as not to duplicate.
php laravel laravel-5 laravel-middleware
Alex May 13 '15 at 10:38 2015-05-13 10:38
source share