Laravel 客制化登入頁面
發表人:
Seachaos
積分: 2432
積分: 2432
這邊使用Laravel內建的User 資料表,可以先加上一些欄位
於 database/migrations/xxxx_create_users_table.php
加上 account 做示範,例如:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('account’); // !!
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
|
然後migrate db, User 的Model fillable 也要填寫
先建立認證用的Controller,這邊叫User
於終端機輸入
php artisan make:controller UserController
|
再來設定router.php,指定我們的登入頁與Controller
Route::get('/login', 'UserController@login');
Route::post('/login', 'UserController@login_check');
|
然後透過 Auth::attempt 來檢查使用者,UserController的範例如下:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use Auth;
use Redirect;
class UserController extends Controller
{
function login(){
return view('user/login');
}
function login_check(){
$account = Input::get('account');
$password = Input::get('password');
if (Auth::attempt(array('account' => $account, 'password' => $password))){ // !!
return Redirect::intended(‘home’);
}
return view('user/login')->withErrors(array(
'msg' => 'Account or Password Error.'
));
}
}
|
withErrors 是在認證失敗,會將原因透過msg給view
view的範例如下:
(於 resources/views/user/login.blade.php )
<form action="{{ url('/mlogin') }}">
{!! csrf_field() !!}
Account:<input type="text" name="nickname" /><br />
Password:<input type="password" name="password" /><br />
@if ($errors->has('msg'))
<span >
<strong>{{ $errors->first('msg') }}</strong>
</span>
@endif
<input type="submit" />
</form>
|