Laravel 5.4:自定义中间件无法正常工作

时间:2017-06-07 15:47:24

标签: php laravel routes laravel-5.3 laravel-middleware

我创建了以下中间件来检查用户会话

<?php

namespace App\Http\Middleware;

use Closure;

class Checkusersession
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->session()->has('admin_name')) {
            // user value cannot be found in session
            return redirect('adminlogin');
        }

        return $next($request);
    }
}

这是我的路线:

 Route::get('webadmin',['middleware' => 'usersession','Admin_controller@index']);

这是我的kernel.php

 protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'usersession' => \App\Http\Middleware\Checkusersession::class,
];

这是我创建会话的控制器方法:

public function auth_admin(Request $request)
{
    $admin_emai = $request->input('admin_email');
    $admin_password = $request->input('admin_password');

    $checklogin = DB::table('admin_login')
        ->select('admin_id','admin_email','admin_name')
        ->where([
            'admin_email' => $admin_email,
            'admin_password' => $admin_password
        ])->first();

    if (count($checklogin) > 0) {
        $request->session()->put('admin_id',$checklogin->admin_id);
        $request->session()->put('admin_name',$checklogin->admin_name);
        $request->session()->put('admin_email',$checklogin->admin_email);

        return redirect()->action('Admin_controller@webadmin');
    } else {
        return redirect()->action('Admin_controller@admin_login_page')->with('status','Incorrect Email ID or Password');
    }
}

我希望中间件检查会话(admin_name)是否存在。如果没有,请将用户重定向到登录页面。但它不起作用。如果我直接从url访问webadmin(仪表板),即使未设置会话,它也可以访问。请帮忙。

1 个答案:

答案 0 :(得分:3)

你的路线错了,你应该把它写成(在L5.4中):

Route::get('webadmin', 'Admin_controller@index')->middleware('usersession');

甚至:

Route::group(['middleware' => 'auth'], function(){
    Route::get('webadmin', 'Admin_controller@index');
});

在L5.3中(因为你已经标记了问题),在L5.4中我想你也可以写:

Route::get('webadmin',['middleware' => 'usersession', 'uses => 'Admin_controller@index']);

另外,您是否尝试在中间件处理函数中执行dd(request());或类似操作,以确定它实际上已被触发?