1.1 登錄成功
在LoginController.php中寫入如下代碼:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class LoginController extends Controller
{
// 登錄顯示
public function index () {
// 指定視圖的模版
return view('admin.login.login');
}
// 登錄 別名 admin.login 根據別名生成url route(別名);
public function login(Request $request) {
// 表單驗證
$post = $this->validate($request, [
'username' => 'required',
'password' => 'required'
], [
'username.required' => '沒賬號還想登錄?你以為你是超人?'
]);
// 登錄
$bool = auth() -> attempt($post);
// dump($bool);
// 判斷是否登錄成功
if ($bool) {
$model = auth() -> user();
// 登錄成功
dump($model -> toArray());
}
}
}
在app/Models/User.php中隱藏密碼欄位:
// 隱藏欄位
protected $hidden = ['password'];

效果:

laravel默認session是存盤在檔案中,優化的話可以優化到memcached或者redis中,
實際專案中登錄成功的話應該展示后臺界面,接下來實作這個功能,
1.1.1 創建后臺控制器和對應的模版
1、創建后臺控制器 php artisan make:controller Admin/IndexController
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class IndexController extends Controller
{
// 后臺首頁顯示
public function index() {
return view('admin.index.index');
}
}
2、后臺首頁路由
// 后臺首頁顯示
Route::get('index', 'IndexController@index') -> name('admin.index');

3、對應的模版 新建index/index.blade.php在U-ui.admin中找到index.html將其復制進去
4、增加歡迎頁面路由
// 歡迎節目路由
Route::get('welcome', 'IndexController@welcome') -> name('admin.welcome');

5、增加控制器方法
// 歡迎頁面
public function welcome() {
return view('admin.index.welcome');
}

6、新建歡迎模板 在U-ui.admin中找到welcome.html將其復制進去

7、修改index.blade.php下的iframe

8、修改LoginController.php中代碼

判斷用戶是否已經登錄過:

1.2 登錄失敗
在LoginController.php中寫入如下代碼:
// withErrors 會把資訊寫入到驗證錯誤資訊提示中 特殊的session laravel中叫閃存
// 閃存 從設定好之后,只能在第1個http請求中獲取到資料,以后就沒有
return redirect(route('admin.login')) -> withErrors(['error' => '登錄失敗']);
效果:

二、退出登錄
退出就是清空session 的程序: auth() -> logout();
2.1 定義退出路由
// 退出
Route::get('logout', 'IndexController@logout') -> name('admin.logout');
2.2 找到退出按鈕

2.3 控制器方法
// 退出
public function logout() {
// 用戶退出
auth() -> logout();
// 跳轉 帶提示
return redirect(route('admin.login')) -> with('success', '請重新登錄');
}
再在common檔案夾下創建msg.blade.php來進行提示型別的判斷:
<!-- 成功 -->
@if(session() -> has('success'))
<div class="Huialert Huialert-success"><i class="Hui-iconfont"></i>
{{session('success')}}
</div>
@endif

再在 login.blade.php 中加入:

效果:


在學習的php的路上,如果你覺得本文對你有所幫助的話,那就請關注點贊評論三連吧,謝謝,你的肯定是我寫博的另一個支持,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/294142.html
標籤:其他
上一篇:《黑馬程式員C++》課程筆記總結
下一篇:【起步】注冊賬號
