Reputation: 825
Suppose I have multiple routes in my Laravel routes.php Like-
Route::post( 'createClan',array('uses'=>'MyClan@createClan'));
Route::post( 'joinClan',array('uses'=>'MyClan@joinClan'));
Route::get( 'myclan', array( 'as' => 'myclan' , 'uses' => 'MyClan@myclan' ));
Route::get( 'clanDetails', array( 'as' => 'clanDetails' , 'uses' => 'MyClan@clanDetails' ));
Route::get( 'myclanDefault', array('as' => 'myclanDefault' , 'uses' => 'MyClan@myclanDefault' ));
And I have Controller named 'Common' and I have a 'ValidateRoute' function inside that common like this-
public function ValidateRoute($UserId, $form_name){
switch ($form_name)
{
case 'createJoin'://Create/Join Clan Menu Option.
$createJoin=TRUE;
$clans= Userclanmapping::where('user_id','=',$UserId)->where('active','=',1)->get(array('clan_id'));
foreach($clans as $clan)
{
$createJoin=FALSE;
}
return $createJoin;
}
}
My problem is that I want to call that function before calling that route. And If the function returns true only then I can open that route but if function returns false I should be moved to another route or I should get a message like route not found.
In short, I am trying to apply a custom check on every route. A route is only accessible only if it fulfills that conditions.
I tried this code-
Route::get( 'myclanDefault', array( 'before'=>'common:ValidateMenuOptions(Session::get(\'userid\'),\'createJoin\'))','as' => 'myclanDefault' , 'uses' => 'MyClan@myclanDefault' ));
But this didn't work.
Upvotes: 0
Views: 446
Reputation: 146219
You can use route filters
per route basis using something like this:
// In filters.php
Route::filter('myclanDefaultFilter', function($route, $request){
// ...
if(someCondition) {
return Redirect::route('routeName');
}
});
Then declare the route
like this:
Route::get(
'myclanDefault',
array(
'before' => 'myclanDefaultFilter',
'as' => 'myclanDefault',
'uses' => 'MyClan@myclanDefault'
)
);
Now before myclanDefault
is dispatched to the action the myclanDefaultFilter
filter will run first and you may redirect from that filter depending a certain condition.
Also, you may declare a global before event
for all the routes using something like this:
App::before(function($request){
// This event will fire for every route
// before they take any further action
});
Upvotes: 1