0

Not sure if this is possible, but here it goes.

What I am looking to do is include my "admin" routes as a separate file, only if the user is an admin (therefore a non admin will get a 404 error

routes.php

if( Session::get('user')->is_admin )
    require_once('routes-admin.php');

if( Auth::check() )
    require_once('routes-user.php');

Route::get('/', function() {
    return view('home');
});

routes-admin.php

Route::get('admin', function() {
    return view('admin-dashboard');
});

routes-user.php

Route::get('user', function() {
    return view('user-dashboard');
});

What I am trying to do is avoid having the test repeated with every single Route so if my user segment has 10 pages I currently need 30 lines of code dedicated to Auth::check() (the if, else and redirect if not), where I can instead have a single check on routes.php and the user will get a 404 if they don't belong

Is there a way to perform this check outside of the Route?

2 Answers 2

2

Perhaps you want to read documentation first?

Route::group(['middleware' => 'auth'], function()
{
    Route::get('/', function()
    {
        // Uses Auth Middleware
    });

    Route::get('user/profile', function()
    {
        // Uses Auth Middleware
    });

});

Above code does exactly what you need, is "person logged in?" let him go to page "whatever".

You can create middlewares (check if user is admin or basic user) yourself and apply on groups.

Example middleware

class BeforeMiddleware implements Middleware
{
    public function handle($request, Closure $next)
    {
        // Perform action

        return $next($request);
    }
}

Do not get me wrong, just your approach is really not Laravel like. Try to see some open source projects done in L5 or even in L4. Try to use everything Taylor already done for you. Documentation is your firend here.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, coming in from 4 I wasn't really thinking about middleware
No problem, in no way you should ever use include() in Laravel app its just bad practise. Please, note that in L4 you have avalible Filters (conceptually same as L5 middlewares).
1

Following the response of @Kyslik for the middleware, you can "include" your own routes file in your RouteServiceProvider like the default routes file, the RouteServiceProvide is located in: app/Providers/RouteServiceProvider.php,

Find the section

require app_path('Http/routes.php');

and just replicate with the name of your routes file want to include

1 Comment

Changed accepted answer because this is closer to what I was looking for with my question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.