简体   繁体   中英

How to get logged in user in a laravel controller constructor

What I want to do is to get the a User's activation status before running any methods and redirect if they're not active. Here's my code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class HomeController extends BaseController
{
    public function __construct(){
        parent::__CONSTRUCT();
        $this->middleware('auth');
        //SEE IF ACTIVE, something like auth()->user()->active
}

    public function home()
    {
        return redirect('/home');
    }
}

Look at the comment on the last line of the constructor, how do I do that?

From 5.3 onwards, you can't directly access session info in a controllers constructor. You can, though, define a Closure based middleware directly in your controller's constructor. More info in the docs

public function __construct()
    {
        $this->middleware('auth');
        $this->middleware(function ($request, $next) {
            if(Auth::user()->active) {
                return Redirect::route('activate');
            }    
            return $next($request);
        });
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM