using laravel auth with different table - laravel

As previously asked I want to use different table(clients) for auth.
I have allready edited some codes, but still I am not able to use auth method.
I've tried too many variations but, still can't login with auth it after user register.
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'client' => [
'driver' => 'session',
'provider' => 'clients',
]
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class,
],
client modal file.
class Client extends Authenticatable
{
protected $guard = 'client';
public $timestamps = true;
protected $fillable = [
'email',
'password',
'fullname',
];
protected $hidden = [
'password', 'remember_token',
];
}
clients migration file.
Schema::create('clients', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('email')->unique();
$table->string('password');
$table->string('fullname');
$table->rememberToken();
$table->timestamps();
});
Controller
public function showRegister()
{
return view('pages.register');
}
public function doRegister(ClientRequest $request)
{
$validated = $request->validated();
$request->merge(['created_at' => Carbon::now()]);
$request->merge(['password' => Hash::make($request->password) ]);
$add = Client::create($validated);
auth('client')->attempt($add);
return redirect('my_profile')->with('success', 'success');
}
After submit register form I get this error.
Symfony\Component\Debug\Exception\FatalThrowableError
Argument 1 passed to Illuminate\Auth\SessionGuard::attempt() must be of the type array, object given, called in C:\wamp64\www\laravel\app\Http\Controllers\HomepageController.php on line 117
when I change my attempt code like this, It returns null.
auth('client')->attempt([
'email'=> $request->email,
'password'=> $request->password
]);

If user is getting created successfully try this line.
auth('client')->login($add);
Remove this line
auth('client')->attempt($add);

Related

middleware('auth') doesn't work when i changed default auth table

So i changed config/auth.php to change default auth table from user to accounts like this :
'defaults' => [
'guard' => 'web',
'passwords' => 'accounts',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'accounts',
],
'api' => [
'driver' => 'token',
'provider' => 'accounts',
'hash' => false,
],
],
'providers' => [
'accounts' => [
'driver' => 'eloquent',
'model' => App\Akun::class,
],
],
i have changed App\Akun Model configuration same as App\User Model :
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Akun extends Authenticatable
{
use HasFactory;
protected $table = 'accounts';
protected $fillable = [
'nip',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
And My Login system is working too. It can return back if the NIP or Password wrong and give error message too. Here my login code:
function checklogin(Request $request){
$this->validate($request,[
'nip' => 'required',
'password' => 'required'
]);
$akun_data = array(
'nip' => $request->get('nip'),
'password' => $request->get('password')
);
if(Auth::attempt($akun_data)){
return redirect('login/successlogin');
}else{
return back()->with('pesan','NIP atau Password salah');
}
}
it was working and return correctly to login/successlogin and run the code in there. But when i tried to add middleware('auth') to the route of login/succeslogin , it'll always return back to login page even when i gave the correct nip and password
Route::get('/login/successlogin',[LoginController::class, 'successlogin'])->middleware('auth');
You can just add a new guard that will be for your accounts table and call it 'accounts' and then in your routes i.e. you can provide route grouping by guard i.e.
Route::middleware('auth:accounts')->group(function () { ...other protected routes... });
I have solved this, My way to change default auth table is correct. But I forgot to add id column there. just add this code in your New Default Auth Table Migration
$table->id();

web guard allows login but admin guard does not allow login

I define a new guard "Admin" to have a multi Auth System User and admin in my project . web guard allows login.But admin guard does not allow login
when I try to login into Admin ,it gives
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'last_sign_in_at' in 'field list' (SQL: update `admins` set `updated_at` = 2020-09-27 12:49:24, `last_sign_in_at` = 2020-09-27 12:49:24, `current_sign_in_at` = 2020-09-27 12:49:24 where `id` = 1)
My users table
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('user_type');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('status')->default(0);
$table->timestamp('last_sign_in_at')->nullable();
$table->timestamp('current_sign_in_at')->nullable();
$table->string('user_click');
$table->timestamp('user_click_time')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
My admin table
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('user_type');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->boolean('status');
$table->rememberToken();
$table->timestamps();
});
}
auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
//admin guard
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
My Middleware CheckRole
public function handle($request, Closure $next)
{
if (!Auth::guard('admin')->check()){
return redirect('admin/login');
}
return $next($request);
}
My Admin.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
//guard
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
//guard End
class Admin extends Authenticatable
{
use Notifiable;
protected $guard ='admin';
protected $hidden = [
'password', 'remember_token',
];
protected $guarded=[];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
My AdminController
public function adminLogin(Request $request){
if ($request->ismethod('post')) {
$data = $request->input();
if ( Auth::guard('admin')->attempt(['email' => $data['email'], 'password' => $data['password'],
'user_type'=>'admin', 'status' => '1'])){
return view('admin.dashboard');
}
else {
return back()->with('error',' Invalid UserName Or Password');
}
}
}
When I tried to login into Admin, It gives error. Any solution ps !
It seems like you have an event listener listening for Auth's LoginEvent and it is setting the last_sign_in_at field on the Model and saving it. Since you are using different models for Authentication it will end up trying to do this on what ever Model is in that event; in this case the Admin model.
You will need to add this field to your admin table, or you will have to check in the listener which Model the event is holding and decide whether to update this field depending on what type that model is.

unable to login as admin in laravel 5.8

I have multi-authentication set up in my laravel app. I am trying to create multiple authentication using default authentication laravel 5.8. I have two tables one is users and other is admins. I have configured the guards for admin. User login works fine, no issues but when I try to login the admin, it doesn't work even if I login with correct credentials. Password field validation works if I use less then 6 character. Please help me to solve this problem.enter code here
My Admin model is
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable {
use Notifiable;
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'title',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Guard setting is
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
AdminLoginController is
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Http\Request;
class AdminLoginController extends Controller {
public function __construct() {
$this->middleware('guest:admin')->except('logout');
}
public function showLoginForm() {
return view('auth.admin-login');
}
protected function guard() {
return Auth::guard('admin');
}
public function login(Request $request) {
//validate the form
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
//attemp to login
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
//Authentication passed...
return 'success';
//return redirect()
//->intended(route('admin.dashboardsdsdsd'));
//if login success then redirect to page
// if not success then redirect to back
}
return redirect()->back()->withInput($request->only('email', 'remember'));
}
}
Route is
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('admin', 'AdminController#index')->name('admin.dashboard');
Route::get('admin/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('admin/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Please help me to resolve this issue, so that admin can login.
There are two main reasons:
First one: your hash password is not correct, so open this website ( which is MD5 Hash Generator) then put any number that you like, take it and create a new admin account directly from database and paste the password then try
Second one: Clear your cache and view :
php artisan view:clear
php artisan cache:clear

different login routes and login views for student and admin

Every laravel newbie struggles with multi auth, I am no exception
I am trying to make student management system. There will two different routs for admin admin/login and for student student/login.
The student can't register itself, but he will be registered by admin.
So a student has only access to student/dashboard, registration of students will be done by the admin on admin/dashboard.
Below is the detail what I have already done:
created migration for both admin and student.
created guard for both admin and student.
modified login controller and added adminLogin and studentLogin methods.
modified RedirectIfAuthenticated middleware
Config/auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'students' => [
'driver' => 'session',
'provider' => 'students',
],
'web-admin'=>[
'driver'=>'session',
'provider'=>'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'students',
'hash' => false,
],
],
'providers' => [
'students' => [
'driver' => 'eloquent',
'model' => App\Student::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'passwords' => [
'students' => [
'provider' => 'students',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'table' => 'password_resets',
'expire' => 60,
],
],
LoginController.php
lass LoginController extends Controller
{
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:web-admin')->except('logout');
$this->middleware('guest:students')->except('logout');
}
public function showAdminLoginForm()
{
return view('admin.login', ['url' => 'admin']);
}
public function adminLogin(Request $request)
{
$this->validate($request, [
'admin_id' => 'required',
'password' => 'required|min:8'
]);
if (Auth::guard('admin')->attempt(['admin_id' => $request->adminid, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/admin/dashboard');
}
return back()->withInput($request->only('admin_id', 'remember'));
}
public function showStudentLoginForm()
{
return view('student.login', ['url' => 'student']);
}
public function studentLogin(Request $request)
{
$this->validate($request, [
'roll_no' => 'required',
'password' => 'required|min:8'
]);
if (Auth::guard('writer')->attempt(['roll_no' => $request->roll_no, 'password' => $request->password], $request->get('remember'))) {
return redirect()->intended('/student/dashboard');
}
return back()->withInput($request->only('roll_no', 'remember'));
}
}
RedirectAuthenticated.php
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->check()) {
if('web_admin'==='$guard'){
return redirect('/admin/dashboard');
}
return redirect('/admin/login');
}
if (Auth::guard($guard)->check()) {
if('students'==='$guard'){
return redirect('/student/dashboard');
}
return redirect('/student/login');
}
return $next($request);
}
}
I have created two folders in the view, student and admin. They both have two files. login.blade.php and dashboard.blade.php
What laravel does it it shows login, and register under auth folder.
I want to give two routes one for /admin/login which return admin.login view.
Same for student /student/login which return student.login view.
I want to remove /register route and make the link to available on admin dashboard , there will be no admin register link.
Also restrict the user from accessing admin area.
**I don't want the whole code, just help me steps and way that I should follow or changes I have to make **
Finally I solved it. I didn't use php artisan make:auth, instead I did it from scratch. Created a fresh project, deleted User.php and the migration.
Created models Student.php and Admin.php along with migrations and controllers.
php artisan make:model Student -mc
php artisan make:model Admin -mc
After than I created guards, I deleted default guard (I don't know It was right to do so, but I felt that if there is no need of default guard and also it was using users table so I deleted).
Here is config/auth.php
'guards' => [
'student'=>[
'driver'=>'session',
'provider'=>'students'
],
'admin'=>[
'driver'=>'session',
'provider'=>'admins'
],
],
'providers' => [
'students'=>[
'driver'=>'eloquent',
'model'=>App\Student::class,
],
'admins'=>[
'driver'=>'eloquent',
'model'=>App\Admin::class,
]
So I have two guards student and admin.
Here is the admin model Admin.php
class Admin extends Authenticatable
{
use Notifiable;
protected $fillable = [
'firstname', 'lastname','admin_id', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
and model Student Student.php
class Student extends Authenticatable
{
use Notifiable;
protected $fillable = [
'firstname', 'lastname','admin_id', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
After this I modified AdminController.php
class AdminsController extends Controller
{
use AuthenticatesUsers;
protected $guard = 'admin';
public function showLogin(){
return view('admin.login');
}
public function dashboard(){
return view('admin.dashboard');
}
public function login(Request $request){
$this->validate($request,[
'admin_id' => 'required',
'password'=>'required|min:8',
]);
if(Auth::guard('admin')->attempt(['admin_id'=>$request['admin_id'], 'password'=>$request['password']])){
return redirect('admin/dashboard');
}
return redirect('/admin');
}
}
Then I created routes Web.php
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin','AdminsController#showLogin');
Route::get('/student','StudentsController#showLogin');
Route::get('/admin/dashboard','AdminsController#dashboard');
Route::get('/student','StudentsController#showLogin');
Route::post('/admin/login','AdminsController#login');
Route::post('/student/login','StudentsController#login');
Now, at this time login works. I still need to do a lot. If any suggestion, I welcome that, please comment below.

laravel 5.4 change authentication users table name

I'm currently using the laarvel5.4 authentication in my application; and I want to change the users table name while keeping its role as it is in the authentication logic, all I need is just to change the name.
It seems that Laravel changer the Auth file and code structure in the latest version, so auth.php doesn't really look as in the previous versions of laravel.
I have done the following so far, but it's still not working gy giving me an error saying that the table users doesn't exist:
1- I have changed the migration's up() and down() functions to create and drop staff table instead of users and run the migration successfully.
2- I have changed the validator() function in RegisterController.
3- I have changed all the 'users' to 'staff' in config/auth.php, as shown in the code:
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'staff',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'staff',
],
'api' => [
'driver' => 'token',
'provider' => 'staff',
],
],
'providers' => [
'staff' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'staff' => [
// 'driver' => 'database',
// 'table' => 'staff',
// ],
],
'passwords' => [
'staff' => [
'provider' => 'staff',
'table' => 'password_resets',
'expire' => 60,
],
],
];
However, in app/User.php I don't know what to change since in the previous versions there used to be a table variable which u need to change its value from users to the new table name but in my class I don't have such thing
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
You can change the table name in the migration file and then change the table name variable in the User.php model.
Example:
class Flight extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'my_flights';
}
https://laravel.com/docs/5.4/eloquent#eloquent-model-conventions
You need just change in two places
1.add this line after hidden array of app/User.php
protected $hidden = [
'password', 'remember_token',
];
protected $table = 'another_table_name';
2.In the RegisterController change the table name in the validator method:
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:another_table_name',
'password' => 'required|string|min:6|confirmed',
]);
}

Resources