A. Apola
A. Apola

Reputation: 131

Laravel 5 restrict access to pages using middleware

I am working on a laravel project and i need to restrict access to some pages such that only authenticated users can view that page.

To do this, created a middleware: php artisan make:middleware OnlyRegisteredUser
and registered it in the $routemiddleware inside App\Http\kernel.php as

'onlyregistereduser' => \App\Http\Middleware\OnlyRegisteredUser::class,

and this is the class. it redirects user to auth/login if not logged in

    public function handle($request, Closure $next, $right=null)
{
    $user = $request->user();

    if ($user && $user->onlyregistereduser()) {
        return $next($request);
    }

    return redirect('auth/login');
}

Here is my route:

Route::get('admin/poem', ['middleware' => 'onlyregistereduser:admin', 'uses'=>'PoemsController@poem']);

admin is a parameter passed to my middleware. It is taken from my user model which has an `enum' column as follows:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
         //...
        $table->enum('rights', ['admin', 'guest'])->nullable();
         // ...
    });
}

Now to restrict access to some of my controller methods, e.g create, i added a constructor to my PoemsController as shown:

public function __construct()
{
   $this->middleware('onlyregistereduser');
}

My problem now is that this caused every single route to the PoemsController to redirect me to the login page. And again after login in, it doesn't take me to the page i intended to visit. it takes me instead to the home page. What i want is to restrict access to only some of the controller methods and not all of them and to be able to redirect to the intended page after user login. I hope you understand my problem. Any help will be greatly appreciated.

Upvotes: 1

Views: 3055

Answers (1)

Ravisha Hesh
Ravisha Hesh

Reputation: 1504

Remove the middleware from constructor, you don't have to add middleware to both route and costructor. That should solve your ". What i want is to restrict access to only some of the controller methods and not all of them" issue.

For othe issue modify your middleware like this

public function handle($request, Closure $next, $right=null)
{
    $user = $request->user();

    if ($user && $user->onlyregistereduser()) {
        return $next($request);
    }
    $request_url = $request->path();
    session()->put('login_refferrer', $request_url);
    return redirect('auth/login');
}

and before redirect user after login

 if(session()->has('login_refferrer')){
  $url = session()->pull('login_refferrer');
  return redirect($url);
}

Upvotes: 1

Related Questions