-- 文章僅供個人學習參考,如有不恰當的地方,希望前輩們指教。--
1、修改config\auth.php配置檔案
'model' => App\Model\Users::class,
'table' => 'users',
2、 修改Users模型類如下:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class Users extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
//使用auth驗證必須繼承接口
use Authenticatable, Authorizable, CanResetPassword;
//修改為自己的使用者表
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
}
3、修改AuthController控制器
class AuthController extends Controller
{
use ThrottlesLogins /* , AuthenticatesAndRegistersUsers*/ ; //因為沒有注冊功能可以将AuthenticatesAndRegistersUsers注釋掉
protected $redirectPath = '/admin';
protected $redirectAfterLogout = '/auth/login'; //登出後的跳轉位址
public function __construct()
{
$this->middleware('guest', ['except' => ['getlogout']]); //在中間件中排除 getlogout函數 ,否則無法登出
}
function login() {
return view('admin.users.login');
}
function getlogout() {
if(Auth::check()){
Auth::logout(); //登出
}
return redirect('/auth/login');
}
function auth(Request $request) {
$user=$request->only(['name','password']);
if(Auth::attempt($user,$request->remember)){ //驗證密碼 通過後合一用Auth::user() 擷取登入使用者資訊 也可以使用 Auth::loginUsingId($user->id) 來登入
return redirect()->intended('/admin');
}else{
return redirect('/auth/login')->withErrors(['login failed'])->withInput($request->except('password'));
}
}
public function redirectPath() //重構未登入時的跳轉位址
{
return '/admin';
}
}
4、修改檔案不同檔案 redirectPath
guest中間件:app/Http/Middleware/RedirectIfAuthenticated.php
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
return redirect('/admin'); //修改登入頁面預設登陸後的跳轉位址
}
return $next($request);
}
auth中間件:app/Http/Middleware/Authenticate.php
public function handle($request, Closure $next)
{
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('auth/login');
}
}
return $next($request);
}
5、添加路由
Route::group(['namespace' => 'Auth','prefix'=>'auth'],function(){
route::get('/login','[email protected]');
route::get('/logout','[email protected]');
route::post('/login','[email protected]');
});
route::get('/admin',['namespace' => 'Admin','middleware' => 'auth'],'[email protected]');
參考教程:http://laravelacademy.org/tutorials/blog
GitHub:https://github.com/CiaraLi/blogtest