有些情境下,我不需要使用表單來提交資料進行使用者註冊,我需要直接在控制器裡進行註冊,我調用下面的方法。
\Illuminate\Foundation\Auth\RegistersUsers::postRegister($data);
我直接調用這個方法,會提示錯誤。
Non-static method Illuminate\Foundation\Auth\RegistersUsers::postRegister() should not be called statically, assuming $this from incompatible context
其實我想知道的是。Laravel 提供了一個 方法用於驗證使用者登入
Auth::attempt(['email' => $email, 'password' => $password])
有沒有類似的方法,我傳入使用者資訊後直接註冊成為會員呢?
回複內容:
有些情境下,我不需要使用表單來提交資料進行使用者註冊,我需要直接在控制器裡進行註冊,我調用下面的方法。
\Illuminate\Foundation\Auth\RegistersUsers::postRegister($data);
我直接調用這個方法,會提示錯誤。
Non-static method Illuminate\Foundation\Auth\RegistersUsers::postRegister() should not be called statically, assuming $this from incompatible context
其實我想知道的是。Laravel 提供了一個 方法用於驗證使用者登入
Auth::attempt(['email' => $email, 'password' => $password])
有沒有類似的方法,我傳入使用者資訊後直接註冊成為會員呢?
首先,你調用方法的對象不是類(class),是特性(trait),不能直接調用,去看原始碼。
其次,你調用的方法不是靜態方法(static),不能如此(::)調用。
最後,Laravel是通過php artisan make:auth命令產生的控制器AuthController來進行使用者註冊的,以下是摘自控制器裡註冊使用者的方法。
(ty0716簡單的答案也同樣告訴了你在控制器裡註冊使用者其實就是通過User模型,將使用者資訊儲存到資料庫而已,所以你可能想多了。除此之外,資料驗證Validation還需要你自己去做。)
/** * Create a new user instance after a valid registration. * * @param array $data * @return User */ protected function create(array $data) { return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); }
Laravel 5.2中內建的make:auth產生的是通用方法,具體的需要根據自己的情況調整。一般來說是不能直接用的,因為資料庫結構不同。建議自己寫方法。
User::create(array( 'name' => 'your name', 'username' => 'your_username', 'email' => 'name@domain.io', 'password' => Hash::make('your_password'),));
在需要登入的路由前加 Route::auth();
你看下
Route::auth();
檔案路徑 vendor/laravel/framework/src/Illuminate/Routing/Router.php 第346行
是不用在routes.php 中指定登入,註冊的路由的