Reputation: 4670
This is what I am trying to accomplish on my routes.php file
if(Auth::user()->isCompany()){
$middleware = "auth.company";
$namespace = 'Company';
} else {
$middleware = "auth.admin";
$namespace = null;
}
Route::group(['prefix' => 'admin'], 'middleware' => $middleware , 'namespace' => $namespace , function(){
Route::get('/','AdminController@getIndex');
Route::get('users', 'UsersController@getIndex');
});
I would like to use the same route group for every user role but would be handled by different controllers under a different namespace based on the users role.
I wouldn't like to put it on the same controller because it would mess up the controller with lots of conditionals.
The problem here is I couldn't access Auth, How should I go about this?
Auth::user()
is null
hence leading to this error Trying to get property of non-object
I am currently logged in . If I remove this piece of code , I am still logged in. This is inside a route group using an auth middleware
UPDATE: I have tried the answer of @samrap . Here is how my routes.php
file looks like . I still get a Trying to get property of non-object
error
<?php
Route::group(['middleware' => 'auth'], function()
{
dd(\Auth::user()->id);
// Insert the code above here ...
});
Upvotes: 2
Views: 601
Reputation: 5673
As it turns out, my previous answer seems to be wrong. In the link I provided, the solution worked for the user but not for you. It also does not work for me. From debugging I came to the conclusion that the user is not yet authenticated when the routes are being registered. This makes sense considering the entire application is dependent on the routes. You can verify this conclusion by adding a check in your routes.php file:
dd(\Auth::check());
The above line will return false
regardless of if the user is logged in or not. At this point in the runtime of the application, the user has not yet been registered from the session. So, you cannot perform the operation you want to in the routes file, which is in my opinion a good thing.
So, what can you do about this?
You can create your own middleware that will perform the conditionals and call the proper controllers based on those conditions. Have a look at these resources for helping you with that:
http://laravel.com/docs/5.0/middleware http://laravel.io/forum/02-17-2015-laravel-5-routes-restricting-based-on-user-type
Upvotes: 1