iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 11
1
Software Development

30天開發與部署 Laravel 專案系列 第 11

Eloquent ORM 實作(1):以註冊為例

確認資料庫有migrate一張user資料表,Model有做好User設定之後,就可以開始實作Eloquent ORM的操作,也就是MVC架構的C可以開始動工囉。

以下針對Laravel專案架構演示如下:

Controller 部分

實現 eloquent ORM 前,需要先引入 Model ,以目前 App\User 為例

use App\User;  

class RegisterController extends Controller
{
	//自訂方法寫在class內
	public function registerAPI(Request $request)
    {

        //method 1 
        $newRegister = new User;
        $newRegister->name = $request->name;
        $newRegister->email = $request->email;
        $newRegister->password = $request->password;
        $newRegister->save();

        //method 2 
        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => $request->password,
        ]);

        return response()->json(['message' => 'register success , please login '], 201);
    }
}

method 1

  • 先建立model實例後save。

method 2

  • 使用模型的 Create 方法
  • 使用需注意table欄位設定是否已nullable的欄位。

這兩種方式都可以寫入資料庫,擇一執行即可。

Router部分

確認controller code之後,需要去設定router確定傳輸方式

範例是使用 API 傳遞,所以寫在 routes/api.php 裡頭 。

Route::post('register', 'Auth\RegisterController@registerAPI');

成果

這次鐵人賽都會使用 postman 來進行檢驗API
https://ithelp.ithome.com.tw/upload/images/20200926/20125263WkMQQQj7QP.png


以上是自己寫一個custom method 透過API註冊的方式。
.
.
.
.
.
但這樣篇幅好像有點少,來聊一下原生web註冊的流程

web註冊

當我們透過 laravel new blog --auth 後會發現 app/Http/Controllers 路徑下之多了一個 auth 的資料夾,裡頭有這些檔案

https://ithelp.ithome.com.tw/upload/images/20200926/20125263hXIR8AH5NY.png

透過 ``php artisna route:list``` 可以確認 Laravel也預設好相關註冊設定
https://ithelp.ithome.com.tw/upload/images/20200926/20125263340tZbru3r.png

所以當我們啟動 php artsian server 後,可以發現index右上角有的 Register。點擊當下會啟動 register的 get (App\Http\Controllers\Auth\RegisterController@showRegistrationForm )方法,呈現以下頁面

https://ithelp.ithome.com.tw/upload/images/20200926/20125263uVMulKHU2k.png

而route內 register的 post,回顧 RegisterController裡頭也會發現到它也使用
User::create這種ORM方式建立資料。

protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);
    }

停止註冊

前幾天的文章中有提到 Auth::routes()隱含很多作法。
但如果只想關掉註冊功能,不影響登入、修改密碼的部分,可在route中調整以下指令

Auth::routes(['register' => false]);  

參考資料
https://laravel.com/docs/7.x/authentication
https://laravel.tw/docs/5.0/authentication
https://ithelp.ithome.com.tw/articles/10226796
https://ithelp.ithome.com.tw/articles/10220541
https://learnku.com/laravel/t/8238/why-do-you-use-your-own-route-instead-of-auth-routes
https://officeguide.cc/laravel-6-create-project-with-user-authentication/


上一篇
Eloquent ORM 前置作業:設定Model
下一篇
Eloquent ORM 實作(2):以登入為例
系列文
30天開發與部署 Laravel 專案30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言