Tutorials, PHP & MySQL, Laravel Framework

Laravel accessing auth in Service Providers

There are times being able to use Auth within service providers is really useful such as showing menus depending on your access level. You cannot directly access Auth within a service provider due to it not yet being loaded. 

One solution to this is View Composers, closures are always loaded before the Auth system making the Auth available to them. View Composers are a way to share variables to all or a set of views.

The View:composer accepts 2 params the view and a closure.

The name of a view can be a single string or an array of views. Also, a wildcard can be used * that load work for all views. In some cases you don't want to do that as the View:composer will run for every view resulting in the same code running multiple times.

In the case where you want it to load once use a master view layout that all other views extend from.

This example shows that auth() can be used as a conditional allowing you to only how menus to authorised users.

View::composer('app', function($view){

    if ( auth()->user()->hasRole('Admin')) {

        \Menu::make('QuickMenu', function ($menu) {
            $menu->add(trans('Roles::module.create.title'), 'roles/create');
        });            
    }
});

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.