2

I searched through the web and none came out the solution in resloving the issue.I am having issue in UserController and in other controllers it is working fine. Let see the route

Route::group(['roles' => ['Super Admin', 'Admin']], function () {
    Route::resource('user','UserController')->middleware(['auth','roles']);
 });

and the UserController

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        print_r(Auth::user());
        exit();
    }
B L Praveen
  • 1,812
  • 4
  • 35
  • 60

2 Answers2

3

middleware including "auth" aren't executed when a controller instance is created. Therefore, Auth::user() always returns null if you call it inside controller's constructor. Only use Auth::user() inside other methods of a controller.

0

You cannot access a session or an authenticated user in the constructor of your controller since the middleware is still starting to run.

The below code will surely help fulfill your requirement.

class UserController extends Controller
{
    public function __construct()
    {
        $this->user_detail;
        $this->middleware(function ($request, $next) {
            $this->user_detail = Auth::user();
            return $next($request);
        });
    }
}

For more detail you could check official document of laravel: https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors

Ketan Chaudhari
  • 329
  • 3
  • 7