Search code examples
http-redirectlaravelroutesposition

Checking the current page in laravel


I have a database which stores the current page the user is on, if they logout or get kicked out, their position (an integer) is stored.

What I am trying to do is when they log back in, I want them to redirect to their pages position. Also if they try and go to page 8 and they have only completed pages 4, they need to get redirected.

I have tried in my PagesContoller constructor and in the before filter which give a redirect loop issue.

App::before(function($request)
{
     $position = DB::table('users')->whereId(Auth::user()->id)->pluck('position');
     return Redirect::to('mypage');

});

I need to check the position and then redirect before anything else. Should this be done in blade?

Edit my routes are jut wrapped in a before filter

Route::group(array('before' => 'auth'), function()
{

    Route::get('page1', array('as' => 'page1', 'uses' => 'PagesController@page1'));
    Route::get('page2', array('as' => 'page2', 'uses' => 'PagesController@page2'));
    Route::get('page3', array('as' => 'page3', 'uses' => 'PagesController@page3'));
    Route::get('page4', array('as' => 'page4', 'uses' => 'PagesController@page4'));
    Route::get('page5', array('as' => 'page5', 'uses' => 'PagesController@page5'));

});

Typically the controller just creates the page, passes a few vars.

   public function page1() {
        $data = array(
        'title'  => 'Page1',
        'questions'  => 'js/page1.js'

    );

    return View::make('page1')->with('data', $data);

}

Solution

  • You could do that in your App::before filter. But before the redirect, you need to check if the current URL path is different from the one you want to redirect to. Because the filter is run on every request, it will create a redirect loop if the current page is the same as the one you want to redirect to. Something like this should work:

    App::before(function($request)
    {
        if (Auth::check())
        {
            $position = DB::table('users')->whereId(Auth::user()->id)->pluck('position');
            $path = 'page' . $position;
    
            if ($request->path() !== $path)
            {
                return Redirect::route('page' . $position);
            }
        }
    });
    

    This also checks for is the user is authenticated, because it needs to use the user ID to query the database.