Laravel Auth Process

Purpose

Create different authentication for both user and admins using Laravel’s default auth process.

Config

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'admin' => [
            'driver' => 'session',
            'provider' => 'admins',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],
    ],

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\UserM::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],
  • Create a guard “admin” and its “provider”.

Model for the provider

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Database\Eloquent\Model;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

use Carbon\Carbon;

class UserM extends Authenticatable{
	use Notifiable;

    protected $table = 'users';
    static $stable = 'users';

    protected $primaryKey = 'id';
    public $timestamps = false;
    const CREATED_AT = 'created_at';
    const UPDATED_AT = 'updated_at';

	protected $fillable = [
        'name', 'account', 'password',
	];
	
	protected $hidden = [
        'password',
	];
	
	protected $guard = 'admin';
}
  • This model has to extend Authenticatable
  • Config some params.

Login Controller

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class MainC extends ParentC
{
    use AuthenticatesUsers;

    protected $redirectTo = '/admin/category';

    public function __construct(){
        parent::__construct();
    }

    protected function guard() {
        return \Auth::guard('admin');
    }

    public function username(){
        return 'account';
    }

    public function login_check(Request $req){
        $account = $req->input('account');
        if($account == false){
            show_alert('Incorrect account', BASE_URL . 'admin/login');
        }

        $password = $req->input('password');
        if($password == false){
            show_alert('Incorrect password', BASE_URL . 'admin/login');
        }
		
        $remember = $req->input('remember');
        if($remember == 'yes'){
            $remember = true;
        }else{
            $remember = false;
        }

        $credentials = [
            'account' => $account, 
            'password' => $password
        ];
        //logg($credentials);
        //logg(Hash::make($password));
        //attemps() will create sessions
        if($this->guard()->attempt($credentials, $remember) == true){
            //logg($this->guard()->check());
            return redirect()->intended('/admin/category');
        }
    }

    public function logout(){
        $this->guard()->logout();
        return redirect()->route('admin.login');
    }
}

Middleware

// app\Http\Middleware\Authenticate.php

    protected function redirectTo($request)
    {
        //var_dump($request->getRequestUri());
        //var_dump($request->is('b2b*'));
        
        if (! $request->expectsJson()) {
            //Start without "/"
            if($request->is('b2b') == true || $request->is('b2b/*') == true){
                //Redirect by route name
                return route('b2b_login');

                //Redirect by url
                //return url('/b2b/login');
            }

            return route('login');
        }
    }

Protection by Route:

Route::group(['prefix'=>'b2b', 'middleware'=>'auth:b2b'], function () {
    Route::get('/', '[email protected]');
});

Protection by middleware

use Illuminate\Support\Facades\Auth;

class CategoryC extends ParentC
{
    $this->user = null;

    public function __construct(){
        parent::__construct();

        $this->middleware('auth:admin');

        $this->middleware(function ($request, $next) {
            //logg(Auth::user());
            $this->user = Auth::user();
 
            return $next($request);
        });
    }

    public function index(Request $req){
        //Auth::guard('admin')->user() -> works
        //Auth::user() -> works
        
        $data['page_title'] = 'Category';
        
        return view('admin.category.index', $data);
    }
}

Reference: