Dùng xác thực có sẵn của Model User, use Illuminate\Foundation\Auth\User as Authenticatable (ok)

app\Models\User.php

Áp dụng vào thực tế

routes\web.php

Route::get('/login-auth', [AuthController::class, 'login_auth'])->name('loginauth');
Route::post('/login', [AuthController::class, 'login'])->name('login');

app\Http\Controllers\AuthController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Admin;
use Auth;
class AuthController extends Controller
{
    public function register_auth(){
    	return view('admin.custom_auth.register');
    }
    public function register(Request $request){
		$this->validation($request);
		$data = $request->all();
		$admin = new Admin();
		$admin->admin_name = $data['admin_name'];
		$admin->admin_phone = $data['admin_phone'];
		$admin->admin_email = $data['admin_email'];
		$admin->admin_password = md5($data['admin_password']);
		$admin->save();
		return redirect('/register-auth')->with('message','Đăng ký thành công');
    }
    public function validation($request){
    	return $this->validate($request,[
    		'admin_name' => 'required|max:255',
    		'admin_phone' => 'required|max:255',
    		'admin_email' => 'required|email|max:255',
    		'admin_password' => 'required|max:255',
    	]);
    }
    public function login_auth(){
        return view('admin.custom_auth.login_auth');
    }
    public function login(Request $request){
        $this->validate($request,[
            'admin_email' => 'required|email|max:255',
            'admin_password' => 'required|max:255'
        ]);
        if(Auth::attempt(['admin_email'=>$request->admin_email,'admin_password'=>$request->admin_password ])){
            return redirect('/dashboard');
        }else{
            return redirect('/login-auth')->with('message','Lỗi đăng nhập authentication');
        }
    }
}

config\auth.php

<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */
    'defaults' => [
        'guard' => 'web',
        'passwords' => 'customusers',
    ],
    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'customusers',
        ],
        'api' => [
            'driver' => 'token',
            'provider' => 'customusers',
            'hash' => false,
        ],
    ],
    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */
    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],
        'customusers' => [
            'driver' => 'eloquent',
            'model' => App\Models\Admin::class,
        ],
    ],
    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */
    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
        'customusers' => [
            'provider' => 'customusers',
            'table' => 'password_resets',
            'expire' => 15,
        ],
    ],
    'socialite' => [
        'drivers' => [
            'google',
        ],
    ],
];

app\Models\Admin.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
    use HasFactory, Notifiable;
    public $timestamp = false;
    protected $table = 'tbl_admin';
    protected $primaryKey = 'admin_id';
    protected $fillable = [
        'admin_email',
        'admin_password',
        'admin_name',
        'admin_phone'
    ];
    public function getAuthPassword(){
        return $this->admin_password;
    }
}
Chú ý: Phải đặt tên hàm đúng như trên thì nó mới thay đổi thành cột admin_password để nó so sánh.

Lý do đặt tên phải giống ở đây

vendor\laravel\framework\src\Illuminate\Auth\EloquentUserProvider.php

resources\views\admin\custom_auth\login_auth.blade.php

<!DOCTYPE html>
<head>
<title>{{ config('app.name', 'Laravel') }}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Visitors Responsive web template, Bootstrap Web Templates, Flat Web Templates, Android Compatible web template,
Smartphone Compatible web template, free webdesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- bootstrap-css -->
<link rel="stylesheet" href="{{asset('assetadmin/css/bootstrap.min.css')}}" >
<!-- //bootstrap-css -->
<!-- Custom CSS -->
<link href="{{asset('assetadmin/css/style.css')}}" rel='stylesheet' type='text/css' />
<link href="{{asset('assetadmin/css/style-responsive.css')}}" rel="stylesheet"/>
<!-- font-awesome icons -->
<link rel="stylesheet" href="{{asset('assetadmin/css/font.css')}}" type="text/css"/>
<link href="{{asset('assetadmin/css/font-awesome.css')}}" rel="stylesheet">
<link rel="stylesheet" href="{{asset('assetadmin/css/morris.css')}}" type="text/css"/>
<!-- calendar -->
<link rel="stylesheet" href="{{asset('assetadmin/css/monthly.css')}}">
<link href="{{asset('css/sweetalert2.min.css')}}" rel="stylesheet">
<link rel="stylesheet" href="{{asset('/css/app.css')}}">
<!-- //font-awesome icons -->
<script src="{{asset('assetadmin/js/jquery2.0.3.min.js')}}"></script>
<script src="{{asset('assetadmin/js/raphael-min.js')}}"></script>
</head>
<body>
<div class="log-w3">
<div class="w3layouts-main">
	<h2>Đăng nhập authentication</h2>
	<?php
	$message = Session::get('message');
	if($message){
		echo '<span class="text-alert">'.$message.'</span>';
		Session::put('message',null);
	}
	?>
		<form action="{{URL::to('/login')}}" method="post">
			@csrf
			@foreach($errors->all() as $val)
			<ul>
				<li>{{$val}}</li>
			</ul>
			@endforeach
			<input type="text"  class="ggg" name="admin_email" placeholder="Điền Email" >
			<input type="password" class="ggg" name="admin_password" placeholder="Điền password" >
			<span><input type="checkbox" />Nhớ đăng nhập</span>
			<h6><a href="#">Quên mật khẩu</a></h6>
			<div class="clearfix"></div>
			<input type="submit" value="Đăng nhập" name="login">
		</form>
		<a href="{{url('/login-facebook')}}">Login Facebook</a> |
		<a href="{{url('/login-google')}}">Login Google</a> |
		<a href="{{url('/register-auth')}}">Đăng ký Auth</a> |
		<a href="{{url('/login-auth')}}">Đăng nhập Auth</a>
		{{-- <p>Don't Have an Account ?<a href="registration.html">Create an account</a></p> --}}
</div>
</div>
<script src="{{asset('assetadmin/js/bootstrap.js')}}"></script>
<script src="{{asset('assetadmin/js/jquery.dcjqaccordion.2.7.js')}}"></script>
<script src="{{asset('assetadmin/js/scripts.js')}}"></script>
<script src="{{asset('assetadmin/js/jquery.slimscroll.js')}}"></script>
<script src="{{asset('assetadmin/js/jquery.nicescroll.js')}}"></script>
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="{{asset('assetadmin/js/flot-chart/excanvas.min.js')}}"></script><![endif]-->
<script src="{{asset('assetadmin/js/jquery.scrollTo.js')}}"></script>
<script src="{{asset('js/sweetalert2.all.min.js')}}"></script>
<!-- morris JavaScript -->
<script type="text/javascript">
    $(document).ready(function() {
        //BOX BUTTON SHOW AND CLOSE
        jQuery('.small-graph-box').hover(function() {
            jQuery(this).find('.box-button').fadeIn('fast');
        }, function() {
            jQuery(this).find('.box-button').fadeOut('fast');
        });
        jQuery('.small-graph-box .box-close').click(function() {
            jQuery(this).closest('.small-graph-box').fadeOut(200);
            return false;
        });
        //CHARTS
        function gd(year, day, month) {
            return new Date(year, month - 1, day).getTime();
        }
    });
</script>
<script type="text/javascript" src="{{asset('assetadmin/js/monthly.js')}}"></script>
<script type="text/javascript">
    $(window).load( function() {
        $('#mycalendar').monthly({
            mode: 'event',
        });
        $('#mycalendar2').monthly({
            mode: 'picker',
            target: '#mytarget',
            setWidth: '250px',
            startHidden: true,
            showTrigger: '#mytarget',
            stylePast: true,
            disablePast: true
        });
    switch(window.location.protocol) {
    case 'http:':
    case 'https:':
    // running on a server, should be good.
    break;
    case 'file:':
    alert('Just a heads-up, events will not work when run locally.');
    }
    });
</script>
@yield('script')
</body>
</html>

app\Http\Controllers\AdminController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Session;
use Illuminate\Support\Facades\Redirect;
class AdminController extends Controller
{
    public function index() {
        return view('admin.custom_auth.login_auth');
    }
    public function dashboard(Request $request) {
        $email = $request->get('email');
        $password = md5($request->get('password'));
        $result = DB::table('tbl_admin')->where('admin_email', $email)->where('admin_password', $password)->first();
        if($result) {
            Session::put('admin_name', $result->admin_name);
            Session::put('admin_id', $result->admin_id);
            return Redirect::to('dashboard');
        }else {
            return Redirect::to('admin');
        }
    }
    public function show_dashboard() {
        return view('admin.dashboard');
    }
    public function logout() {
        Session::put('admin_name',null);
        Session::put('admin_id',null);
        return Redirect::to('admin');
    }
}

Source Code

Last updated

Was this helpful?