iT邦幫忙

第 11 屆 iThome 鐵人賽

1
Modern Web

30天成為Laravel萌新系列 第 31

30天成爲Laravel萌新(第30天) - 登入驗證

這部份在Django時,明明是最先學的,在Laravel卻放到了最後☺

要使用Laravel提供的會員系統,相當容易,只須要:

artisan make:auth
artisan migrate

然後瀏覽http://localhost/register 註冊帳號,或是http://localhost/login 登入帳號。仔細一看,會多了這些檔案:

	new file:   app/Http/Controllers/HomeController.php
	new file:   resources/views/auth/login.blade.php
	new file:   resources/views/auth/passwords/email.blade.php
	new file:   resources/views/auth/passwords/reset.blade.php
	new file:   resources/views/auth/register.blade.php
	new file:   resources/views/auth/verify.blade.php
	new file:   resources/views/home.blade.php
	new file:   resources/views/layouts/app.blade.php
	modified:   routes/web.php

其中routes/web.php多了:

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

現在瀏覽http://localhost/home 也有畫面了。

客製化頁面

在知道哪些檔案被加入後,也可以很容易的知道怎麼修改頁面。是的,就是修改resources/views/auth/裡的模板。還有home.blade.php。當然,如果你喜歡Laravel預設的排版的話,也可以將繼承改成:

@extends('layouts.app')

操作帳號

帳號相關的操作都在Auth,像是你可以這樣取得此次連線中登入的帳號:

use Illuminate\Support\Facades\Auth;

// 取得帳號
$user = Auth::user();

// 取得ID
$id = Auth::id();

Auth::check()檢查是否登入了。

use Illuminate\Support\Facades\Auth;

if (Auth::check()) {
    // The user is logged in...
}

或是用Auth::attempt()手動檢查

        if (Auth::attempt(['email' => $email, 'password' => $password])) {
            // pass
            return redirect()->intended('dashboard');
        }

直接允許登入使用特定帳號:

Auth::login($user);
// or
Auth::login($user, true);

強置清除登入資訊:

Auth::logout();

Laravel的身份驗證機制可以很簡單的使用,但也有非常豐富的用法。甚至有提供OAuth2、API驗證的方式。更多可以參考:


上一篇
30天成爲Laravel萌新(第29天) - 表單驗證
下一篇
30天成爲Laravel萌新(第30-1天) - 總結
系列文
30天成為Laravel萌新32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言