Laravel 5 new auth: Get current user and how to implement roles? Laravel 5 new auth: Get current user and how to implement roles? php php

Laravel 5 new auth: Get current user and how to implement roles?


After spending some more time on Laravel 5 I can an answer my own question:

Is injecting Guard the recommended way? No: If you need to access Auth in your view, you can do so already like this:

@if( Auth::check() )    Current user: {{ Auth::user()->name }}@endif

This uses the Auth facade. A list of all available facades is in config/app.php under aliases:

What if I need Auth in my controller? Injecting an instance of Guard like shown in the question works, but you don't need to. You can use the Auth facade like we did in the template:

    public function index()    {        if(\Auth::check() && \Auth::user()->name === 'Don') {            // Do something        }        return view('client.index');    }

Be aware that the \ is needed before the facade name since L5 is using namespaces.

I want to have permissions/roles using the new auth mechanism in L5: I implemented a lightweight permission module using the new middleware, it is called Laraguard. Check it out on Github and let me know what you think: https://github.com/cgrossde/Laraguard

UPDATE: For the sake of completeness I want to mention two more projects. They provide everything you need to save roles and permissions in the DB and work perfectly together with Laraguard or on their own:


If you want make your own custom authentification, you need to keep the User model from Laravel 5 with all the dependency. After you will be able to login your user in your controller. Dont forget to put (use Auth;) after the namespace of your controller.