vipmaa vipmaa - 1 year ago 251
PHP Question

i get Auth::user is null in laravel

i create middleware for admin role using following code

php artisan make:middleware AdminMiddleware

after that i create route for login page

Route::get('admin/login', ['middleware'=>'web','as'=>'admin.login','uses'=>'AdminController@loginView']);
Route::group(['prefix'=>'admin','middleware' => ['auth.admin','web']], function()
Route::get('/', ['as'=>'admin.home','uses'=>'AdminController@index']);
Route::get('/home', ['as'=>'admin.home','uses'=>'AdminController@index']);


and controller is

class AdminController extends Controller
function index(){
return 'welcome';

function loginView(){
return view('admin.login');
function login(Request $request){
$error = $this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:5',
$email = $request->input('email');
$password = $request->input('password');
$remember = $request->input('remember');

if (Auth::attempt(['email' => $email, 'password' => $password,'type'=>'admin'], $remember)) {
// Authentication passed...
Auth::login(Auth::user(), $remember);
return redirect()->route('admin.home');
}else{//('message', 'Login Failed')
return redirect()->route('admin.login')->withErrors($request->all(), "message")->withInput();

and in AdminMiddleware

public function handle($request, Closure $next)
return redirect()->route('admin.login')->withErrors('You are not logged in');
}elseif ($request->user()->type != 'admin'){
return redirect()->route('admin.login')->withErrors('You have not authority');
return $next($request);

the error is i get alwys null for each $request->user() or Auth:user in AdminMiddleware

Answer Source

You're passing the middleware to the route group in an incorrect order.

Right now you have this order ['auth.admin', 'web'] which means that the auth.admin middleware will be executed before the middleware from the web group, and since web contains the StartSession middleware, you won't have any session in auth.admin which is needed to get the authenticated user.

So simply switch the middleware order like so:

Route::group(['prefix'=>'admin','middleware' => ['web', 'auth.admin']], function () {
    // now the session is set up in `web` and then you have it in `auth.admin`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download