iT邦幫忙

2025 iThome 鐵人賽

DAY 18
0
Modern Web

Laravel 是甚麼系列 第 18

會員註冊開始~

  • 分享至 

  • xImage
  •  

會員註冊要安裝
在terminal下指令composer require laravel/passport --with-all-dependencies
顯示

https://ithelp.ithome.com.tw/upload/images/20250825/20119035O57ibcoFEq.png

在terminal下指令php artisan migrate安裝相對資料庫
https://ithelp.ithome.com.tw/upload/images/20250825/201190355EFfQ3irGG.png
到資料庫重新整理查看:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035LWXaDW7qMO.png
在terminal下指令php artisan passport:install
產生必要的檔案
PS C:\Users\jzs2h\Desktop\code\blog> php artisan passport:install
PHP Deprecated: Illuminate\Log\Logger::__construct(): Implicitly marking parameter $dispatcher as nullable is deprecated, the explicit nullable type must be used instead in C:\Users\jzs2h\Desktop\code\blog\vendor\laravel\framework\src\Illuminate\Log\Logger.php on line 43
Encryption keys generated successfully.
Personal access client created successfully.
Client ID: 1
Client secret: CmW1i1GQZo5ekbDL9tWRnqIOhvVVcIRAZnLhTk59
Password grant client created successfully.
Client ID: 2
Client secret: SX3C5sLcOyCpS6VjIMSyTjFoY9vck3V5C1DK57Q9
https://ithelp.ithome.com.tw/upload/images/20250825/20119035uqjpkzYRg5.png
修改User程式碼:
修改前:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035h66HiH63ha.png

修改後:
加入套件:此為原來就有寫
https://ithelp.ithome.com.tw/upload/images/20250825/20119035sn6B3KrpIr.png
先改成跟老師的 1樣use Laravel\Passport\HasApiTokens;
https://ithelp.ithome.com.tw/upload/images/20250825/20119035ecnQJSVzrk.png
AuthServiceProvider修改前程式碼
https://ithelp.ithome.com.tw/upload/images/20250825/20119035JAJ8z72nBI.png
修改後加入套件: use Laravel\Passport\HasApiTokens;
https://ithelp.ithome.com.tw/upload/images/20250825/201190352EPJTr6AZO.png

往下拉修改程式碼Passport::routes();
https://ithelp.ithome.com.tw/upload/images/20250825/20119035B9beigpo8Z.png

     <?php

namespace App\Providers;

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Gate;
use Laravel\Passport\HasApiTokens;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        //
        Passport::routes();
    }
}

修改auth.php 程式碼
修改前程式碼
https://ithelp.ithome.com.tw/upload/images/20250825/20119035db4QWeEXtY.png
修改後程式碼
加入'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],

https://ithelp.ithome.com.tw/upload/images/20250825/20119035xw1WT0nVLE.png

用指令php artisan make:controller AuthController
加入controller
https://ithelp.ithome.com.tw/upload/images/20250825/20119035mIKANXvaEa.png
修改AuthController程式碼:建立會員資料
https://ithelp.ithome.com.tw/upload/images/20250825/20119035u9sB4Bmafn.png
會員資料的驗證
先下指令: php artisan make:request CreateUser
在request資料夾下面產生檔案CreateUser
https://ithelp.ithome.com.tw/upload/images/20250825/20119035iZBLDK5EI4.png
CreateUser自動產生的程式碼:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateUser extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

https://ithelp.ithome.com.tw/upload/images/20250825/20119035ox1fl9HVPK.png

修改程式碼內容:

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CreateUser extends APIRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            //
        ];
    }
}

https://ithelp.ithome.com.tw/upload/images/20250825/20119035h5M3C6SY3o.png

對照users資料表寫rules
https://ithelp.ithome.com.tw/upload/images/20250825/20119035ZuKl9fQdsA.png
繼續修改CreateUser程式碼內容:
'email' => 'required|string|email|unique:users',其中email的unique表示唯一
'password' => 'required|string|confirmed'其中password的confirmed'表示密碼輸入後,再次確認

https://ithelp.ithome.com.tw/upload/images/20250825/20119035mqMkEb8fob.png

修改AuthController程式碼:

修改前程式碼:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    //
    public function signup(Request $request)
    {
        $form = $request->all();
    }
}

https://ithelp.ithome.com.tw/upload/images/20250825/201190355Bs09hYHaY.png

https://ithelp.ithome.com.tw/upload/images/20250825/20119035bCj2CtCj8g.png
修改後程式碼:
加入套件
密碼使用bcrypt去加密
https://ithelp.ithome.com.tw/upload/images/20250825/2011903585BMNuyAgn.png
設定 路由
https://ithelp.ithome.com.tw/upload/images/20250825/201190356hfY6KlDF6.png
在terminal執行php artisan serve
https://ithelp.ithome.com.tw/upload/images/20250825/20119035ne2r9fNpMi.png
用POSTMAN測試

https://ithelp.ithome.com.tw/upload/images/20250825/201190353r2oD6VaiW.png
到資料庫查看
https://ithelp.ithome.com.tw/upload/images/20250825/20119035bwFtXyKVQI.png
再註冊一次會說EMAIL已使用過
https://ithelp.ithome.com.tw/upload/images/20250825/20119035rTZErneJDm.png
AuthController加入登入的通行證:
修改前的程式碼:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\CreateUser;
use App\Models\User;

class AuthController extends Controller
{
    //
    public function signup(CreateUser $request)
    {
        $validatedData = $request->validated();
        $user = new User([
            'name' => $validatedData['name'],
            'email' => $validatedData['email'],
            'password' => bcrypt($validatedData['password'])
        ]);
        $user->save();
        return response('success', 201);

    }
}

修改後的程式碼:
加入套件:
https://ithelp.ithome.com.tw/upload/images/20250825/201190353gnQBCCgFT.png
加入程式碼:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035rZxEFH37oP.png
擴充路由:

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::resource('products', 'ProductController'); 
Route::resource('carts', 'CartController'); 
Route::resource('cart-items', 'CartItemController'); 
Route::post('signup','AuthController@signup');
Route::post('login','AuthController@login');

https://ithelp.ithome.com.tw/upload/images/20250825/20119035IBrddbpaNE.png

在terminal重新啟動php artisan serve
用POSTMAN測試錯誤的帳號密碼
https://ithelp.ithome.com.tw/upload/images/20250825/20119035oSvMsznLgW.png
POSTMAN輸入正確的:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035QWvozCE95h.png

https://ithelp.ithome.com.tw/upload/images/20250825/20119035sfeESmtZBf.png
修改程式碼:帶出裡面的資料

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests\CreateUser;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
    //
    public function signup(CreateUser $request)
    {
        $validatedData = $request->validated();
        $user = new User([
            'name' => $validatedData['name'],
            'email' => $validatedData['email'],
            'password' => bcrypt($validatedData['password'])
        ]);
        $user->save();
        return response('success', 201);

    }
    public function login(Request $request)
    {
       
        $validatedData = $request->validate([
            'email' => 'required|string|email',
            'password' => 'required|string'
        ]);

        if(!Auth::attempt($validatedData)){
            return response('授權失敗',401);
        }
        $user = $request->user();
        //dd($user);
    }
}

無法顯示圖片的部分~再麻煩將連結貼上就可以看到了喔

帶出裡面的資料:要選Preview看
https://ithelp.ithome.com.tw/upload/images/20250825/2011903561JPj1MSla.png

dd要刪掉,建立通行證:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035pu8xj7DaKi.png

https://ithelp.ithome.com.tw/upload/images/20250825/20119035wNi6tGOAMf.png
將createToken複製貼上到
https://ithelp.ithome.com.tw/upload/images/20250825/20119035zgZuJEcZOz.png
用指令去調整token下指令: composer require lcobucci/jwt:3.3.3
再terminal下指令去啟動: php artisan serve
修改程式碼:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035euxVHRsLYO.png
用POSTMAN查看
https://ithelp.ithome.com.tw/upload/images/20250825/20119035IiMbazaFPP.png
修改程式碼存入資料庫:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035b5xpAZHMgc.png
用POSTMAN查看
第4章的單元13的10:36看不到跟老師一樣的TOKEN畫面(已提問)
https://ithelp.ithome.com.tw/upload/images/20250825/20119035TvfUMOXIhq.png
到https://jwt.io/網站
https://ithelp.ithome.com.tw/upload/images/20250825/20119035ncb0pv5eXx.png
貼上token:顯示裡面的資料
https://ithelp.ithome.com.tw/upload/images/20250825/20119035xRFOsqwhjs.png
oauth_access_tokens資料表也可以看到:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035Vjd9TJ6ZdV.png
oauth_personal_access_clients資料表也可以看到:
https://ithelp.ithome.com.tw/upload/images/20250825/20119035sstUoTHYZD.png
oauth_clients資料表也可以看到:
https://ithelp.ithome.com.tw/upload/images/20250825/2011903505q8f3SNvd.png
oauth_access_tokens資料表記錄主要資料:
https://ithelp.ithome.com.tw/upload/images/20250825/201190357jQX0jJSTq.png

大家明天見~


上一篇
假刪除
下一篇
要有token才可以
系列文
Laravel 是甚麼30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言