Elaine Marley
Elaine Marley

Reputation: 2213

Laravel custom filter

I need to be able to access a number of routes only if a condition is met. Else I should not have access to those routes.

I thought this should be done with a filter but I think I'm missing something about how they work.

So this is my filter:

Route::filter('my.filter', function()
{
    //some code regarding said condition
    if($mycondition==true){
        //WHAT TO PUT HERE?
    }else{
        //Error message
    }
}

And in my routes I will have:

Route::group(array('before' => 'my.filter'), function()
{
    Route::resource('cities', 'CitiesController');
    //... many more controllers here
});

But all the examples I have seen have a redirect inside the filter in the if part. I don't want that, I only want, if the condition in the filter is true, you get to see that url.

Upvotes: 0

Views: 908

Answers (2)

lukasgeiter
lukasgeiter

Reputation: 152870

If you wanna have your filter stop further Execution of your routes (and controllers and so on) you have to:

  • Return something (e.g. a Redirect)
  • or throw an Exception

In Laravel you can do this pretty easily:

Route::filter('my.filter', function()
{
    //some code regarding said condition
    if($mycondition==true){
        // here you have to do nothing so you could also flip the if...
    }else{
        App::abort(403);
    }
}

Official Docs

Little sidenote: As mentioned above in the comment i would flip the if. Like that:

Route::filter('my.filter', function()
{
    //some code regarding said condition
    if($mycondition==false){
        App::abort(403);
    }
}

Upvotes: 2

Jerodev
Jerodev

Reputation: 33186

You don't have to put anything there, just let the function return void. That will tell laravel that the user is allowed to see the page. You can always put a return there yourself to let the user see the page and skip all the following conditions.

When the condition is not met, it is better to redirect the user to a page where you explain why the user isn't able to see the page.

Route::filter('my.filter', function()
{
    //some code regarding said condition
    if($mycondition==true){
        return;
    }else{
        //Error message
    }
}

Upvotes: 0

Related Questions