Laravel 5.4中的Auth中间件

时间:2017-05-12 18:00:08

标签: php laravel

我在laravel中遇到了中间件的问题。我想制作一个允许注册用户登录的中间件。并且'是'我知道我可以通过'php artisan make:auth'得到它但我想要制作我自己的中间件。 如果我输入url'/ dashboard',它会将我重定向到仪表板,这是非常糟糕的 并且还适用于登录

所以我写了中间件:

<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class AuthUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::guard()->guest()) {
            return redirect()->route('home');
        }
        return $next($request);
    }
}

然后将其添加到kernel.php中的路由:

'auth_user'=>\App\Http\Middleware\AuthUser::class           

以下是我的路线:

    Route::get('/', function () {
    return view('welcome');
})->name('home');

Route::post('/signup',[
    'uses'=>'UserController@postSignUp',
    'as'=>'signup'
]);
Route::post('/signin',[
    'uses' =>'UserController@postSignIn',
    'as'  =>'signin'
]);

Route::group(['middleware'=>['auth_user']],function (){
    Route::get('/dashboard',[
        'uses'       =>  'UserController@getDashboard',
        'as'        =>  'dashboard',
    ]);
});

我的UserController:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;

class UserController extends Controller
{
    public function getDashboard()
    {
        return view('dashboard');
    }
    public function postSignUp(Request $request)
    {
        $this->validate($request,[
            'email'     =>  'email|unique:users',
            'first_name'=>  'required|max:128',
            'password'  =>  'required|min:6'
        ]);
        $email=$request['email'];
        $password=bcrypt($request['password']);
        $first_name=$request['first_name'];
        $surname=($request['surname']);
        $user=new User();

        $user->email=$email;
        $user->password=$password;
        $user->first_name=$first_name;
        $user->surname=$surname;

        $user->save();
        Auth::login($user);
        return redirect()->route('dashboard');
    }
    public function postSignIn(Request $request)
    {
        $this->validate($request,[
            'email'     =>  'required|email',
            'password'  =>  'required|min:6'
        ]);

 if(Auth::attempt(['email'    => $request['email'], 'password'       
            =>$request['password']]))      
        {

            return redirect()->route('dashboard');
        }
            return redirect()->back();
    }
}

1 个答案:

答案 0 :(得分:1)

你不需要拥有网络&#39;在routes / web.php中定义路由时的中间件。

默认情况下,它通过您的RoutingServiceProvider应用于routes / web.php路由

Route::group(['middleware'=>['auth_user']],function (){
    Route::get('/dashboard',[
       'uses'       =>  'UserController@getDashboard',
       'as'        =>  'dashboard',
    ]);
});