3
votes

In my admin pages, I want to manage my ecommerce products using AngularJS.

e.g. admin/product which will query an api in admin/api/product

I have not yet set up user authentication so I dont yet know if the user is an admin user or not.

I only wish to include angularjs admin scripts on admin pages.

Is there a way I can include an angular adminapp.js in my view only if the route group is admin. e.g. for public facing pages, I don't expose the adminapp.js to public facing pages.

I know I can do this if the user is authenticated as admin - but I wish to be able to do this if the route group is admin.

Route::group(['prefix' => 'admin', 'namespace' => 'Admin'], function() {
    Route::group(['prefix' => 'api', 'namespace' => 'Api'], function() {
        Route::resource('product', 'ProductController');
    });

    Route::group(['namespace' => 'Product'], function() {
        Route::get('product', 'ProductController');
    });
});

And in the templates.master.blade.php something like:

@if($routeGroupIsAdmin)
    {{ HTML::script('js/adminapp.js') }}
@endif

or even:

{{ Route::getCurrentRoute()->getPrefix() == 'admin'? HTML::script('js/adminapp.js') : HTML::script('js/app.js') }}

But the problem with above example is that if I am in a deep nested view: admin/categories/products then my prefix will no longer be admin. I don't want to go down the route of using a regex to detect the word admin in the route prefix.

2

2 Answers

5
votes

There's no built in way that I know of, but here's something that works:

First, add a route filter

Route::filter('set-route-group', function($route, $request, $value){
    View::share('routeGroup', $value);
});

Then add this to your admin group (you can also use it for other groups in the future):

Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'before' => 'set-route-group:admin'], function(){

Also add this at the top of the routes file to make sure the $routeGroup variable is always set:

View::share('routeGroup', null);

Then in your view:

@if($routeGroup == 'admin')
    {{ HTML::script('js/adminapp.js') }}
@endif
2
votes

You can use the route segments.

if your group prefix is 'admin' and the URL looks like this http://example.com/admin/home, You can just check it on the blade using Request::segment(1). it renders the first segment of the URL.

@if(Request::segment(1) == 'admin')
   {{HTML::script('js/adminapp.js')}}
@endif

If you are checking another segment just change the index.