laravel auth 登入
阿新 • • 發佈:2019-01-24
建立model層名稱為 Admin.php 內容為
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Cartalyst\Sentinel\Users\EloquentUser; use Illuminate\Foundation\Auth\User as Authenticatable; class Admin extends Authenticatable { // }
命令執行 php artisan make:auth
在app/Http/Kernel.php 中 刪除
\App\Http\Middleware\TrustProxies::class,在 api組中註釋掉 'throttle:60,1'
在 $routeMiddleware組中新增 'admin'=> \App\Http\Middleware\Admin::class,
在app/config中的auth.php中 新增
guards 組中新增
'admin'=>[ 'driver'=>'session', 'provider'=>'admin', ],
providers 組中新增
'admin'=>[ 'driver'=>'eloquent', 'model' => App\Models\Admin::class, ],
在app/Http/Middleware中 新建 Admin.php 內容為
<?phpnamespace App\Http\Middleware; use Illuminate\Support\Facades\Auth; use Closure; class Admin { public function handle($request, Closure $next) { if (Auth::guard('admin')->check()) { // The user is logged in...return $next($request); }else{ return redirect('Admin/Login'); } } }
控制器內容為
<?php namespace App\Http\Controllers\Admin; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class LoginController extends Controller {public function postLogin(Request $request) { $name = $request->get('name'); // 使用者名稱 $password = $request->get('password'); if (empty($name) && empty($password)) return back()->with(['msg'=>'使用者名稱和密碼不能為空!']); $arr = [ 'name' => $name, 'password' => $password ]; if (Auth::guard('admin')->attempt($arr)){ return redirect()->action('後臺首頁地址'); }else{ return redirect('登入地址')->with(['msg'=>'使用者名稱或密碼不正確!']); } } }