I am trying to Auth Attempt for login in Laravel. and Successfully Logged . But can't Remember Auth Session.
My kernel.php file :
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
Auth.php file is:
<?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' => 'users',
],
/*
|--------------------------------------------------------------------------
| 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' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| 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\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| 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,
],
],
];
HomeController.php Code is :
public function login(Request $request){
if($request->isMethod('post')){
$data = $request->all();
$any = array('email'=>$data['email'],'password'=>$data['password']);
if(auth()->attempt($any)){
dd("logged"); //This code is running when i try to login
//but after when i try to get Auth::check() then it return false
}
}
}
My web.php File :
<?php
Route::group(['middleware'=>'web'],function(){
Route::match(['get','post'],'/', 'HomeController#index');
Route::match(['get','post'],'/login', 'HomeController#login');
Route::group(['middleware'=>'auth'],function(){
});
});
?>
Did you tried to Authenticate users by calling so:
Auth::attempt($user_credentails);
instead of auth()
I solved this problem. Let's check my HomeController code
public function login(Request $request){
if($request->isMethod('post')){
$data = $request->all();
$any = array('email'=>$data['email'],'password'=>$data['password']);
if(auth()->attempt($any)){
dd("logged"); //This code is running when i try to login
//but after when i try to get Auth::check() then it return false
}
}
}
when auth attempt is successful then i stop code with dd("Logged"); if i stopped code then the auth attempt is not full completed. I removed dd("Logged"); then i make redirect to dashboard.
if(auth()->attempt($any)){
return Redirect('/dashboard');
}
Then i check auth with Auth::check() and it return true . Thanks Guys for Posting Your Valuable Comments and Answers . I really Appreciate it.
Related
This is the config/auth.php
I have edited the auth the student provider
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
' => 'users',
],
/*
|--------------------------------------------------------------------------
| 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' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'student' => [
'driver' => 'session',
'provider' => 'students',
],
],
/*
|--------------------------------------------------------------------------
| 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,
],
'students' => [
'driver' => 'eloquent',
'model' => App\Models\Student::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| 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,
'throttle' => 60,
],
'students' => [
'provider' => 'students',
'table' => 'password_resets',
'expire' => 15,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];
this is my student model
i have edited the student model using the user model as base
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Student extends Authenticatable
{
use HasFactory, Notifiable;
protected $guard = 'student';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
'birthdate',
'Course',
'Year',
];
/**
* 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',
];
}
This is my Student LoginController
My login controller return the login form and below is the login attempt that always return false so it always redirect me back to the login page.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
// use App\Http\Controllers\Auth\LoginController ;
// use Illuminate\Foundation\Auth\AuthenticatesUsers;
class Student_loginController extends Controller
{
// public function __construct()
// {
// $this->middleware('guest:student')->except('logout');
// }
public function index(){
return view('auth.student_login');
}
public function login(Request $request){
$this->validate($request,
[
'email' => 'required|email',
'password' => 'required',
]);
if(Auth::guard('student')->attempt($request->only('email','password'))){
return redirect()->back()->with('failed',' student not successfully logged in');
}
return redirect('student_dashboard')->with('success','student login');
}
}
this is my route
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\RegistrationController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\LoginController;
use App\Http\Controllers\LogoutController;
use App\Http\Controllers\WelcomeController;
use App\Http\Controllers\StudentController;
use App\Http\Controllers\Student_loginController;
use App\Http\Controllers\student_dashController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/',[WelcomeController::class, 'index'])->name('welcome');
Route::get('register',[RegistrationController::class, 'index'])->name('register');
Route::get('dashboard',[DashboardController::class, 'index'])
->name('dashboard')
->middleware('auth');
Route::get('student_dashboard',[student_dashController::class, 'index'])
->name('student_dashboard');
Route::get('login',[LoginController::class, 'index'])
->name('login')
->middleware('guest');
Route::get('logout',[LogoutController::class, 'logout'])->name('logout');
Route::get('student_login',[Student_loginController::class, 'index'])->name('student_login');
Route::get('student',[StudentController::class, 'index'])->name('student')->middleware('auth');;
Route::get('student/{student_ID}', [StudentController::class, 'show'])->name('student.showstudent')->middleware('auth');;
Route::post('register',[RegistrationController::class, 'store'])->name('register.store');
Route::post('store_student', [RegistrationController::class, 'store_student'])->name('store_student')->middleware('auth');
Route::post('student_login',[Student_loginController::class, 'login'])->name('student_login.login');
Route::post('login',[LoginController::class, 'login'])->name('login.login');
Route::post('student',[StudentController::class, 'store'])->name('student.store')->middleware('auth');;
Route::delete('student/{student_ID}',[StudentController::class, 'destroy'])->name('student.destroy')->middleware('auth');;
Route::put('showstudent/{student_ID}',[StudentController::class, 'edit'])->name('showstudent.edit')->middleware('auth');;
// Route::get('/', function () {
// return view('welcome');
// });
if(Auth::guard('student')->attempt($request->only('email','password'))){
return redirect()->back()->with('failed',' student not successfully logged in');}
Your are redirecting back with a failed message when login is true. You have redirect back with a failed message when login is fail. You have to write the logic like this.
if(!Auth::guard('student')->attempt($request->only('email','password'))){
return redirect()->back()->with('failed',' student not successfully logged in');}
Last you have to protect student_dashboard route with middleware auth with its guard
auth:student
Route::middleware('auth:student')->group(function(){
Route::get('student_dashboard',[student_dashController::class, 'index'])
->name('student_dashboard');}
or return the middleware in your dashboard controller contsructor method like this
public function __construct()
{
$this->middleware('auth:student');
}
When i am trying to change the table users, that is by default linked with the Auth in laravel my API always gives me "unauthorized user" response and when i use the default table user it works fine. I want to know why it is happening?
I have made all the changes that is required to switch the table from users to my choice table.
my table name is : apitable, Model_name: apitablemodel
changes in 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' => 'api',
'Passwords' => 'apitable', //if want to change the table attached with auth then make changes here
],
/*
|--------------------------------------------------------------------------
| 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' => 'apitabel',
],
'api' => [
'driver' => 'passport',
'provider' => 'apitable',
],
],
/*
|--------------------------------------------------------------------------
| 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\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
'apitable' => [
'driver' => 'eloquent',
'model' => App\apitablemodel::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| 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,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
'apitable' => [
'provider' => 'apitable',
'table' => 'password_resets',
'expire' => 60,
],
],
];
Here is my model file
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
// use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class apitablemodel extends Authenticatable
{ use HasApiTokens, Notifiable;
//
protected $table='apitable';
protected $fillable = ['Email', 'Password','token'];
public $timestamps=false;
protected $hidden = [
'Password', 'token',
];
}
Here is my controller file
<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\apitablemodel;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
// response()->json(['success' => $success], $this-> successStatus);
class product extends Controller
{ public $successStatus = 200;
public function login(Request $request){
if(Auth::check(['Email' => request('Email'), 'Password' => request('Password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$user->token=$success['token'];
// $token->expires_at=Carbon::now()->addMinutes(1);
$user->save();
return response()->json(["token_expires in :"=>"2min","token"=>$user->token]);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
public function update(Request $req){
$obj= User::find($req->id);
$obj->email=$req->email;
if($obj->save()){
return response()->json(['success'=>'Updated']);
}
else{
return ["status:"=>"Unauthorized user, make sure your are login"];
}
}
}
I have two functions in my controller, one is for updating the data that is present in the "apitable" table and one for login so that only authenticated users can update the database table values.
When i hit my API in postman it gives me unauthorized response as for which i have write the condition in my controller. I want to know why if condition is failing.
I think you should use Auth::attempt() method for login.
public function login(Request $request){
$credentials = $request->only('Email', 'Password');
if(Auth::attempt($credentials)){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
$user->token=$success['token'];
// $token->expires_at=Carbon::now()->addMinutes(1);
$user->save();
return response()->json(["token_expires in :"=>"2min","token"=>$user->token]);
} else {
return response()->json(['error'=>'Unauthorised'], 401);
}
I have a table called customusers. I want to authenticate from this table. I am successful in registering the users and storing in customusers table but i am not able to login using Auth::atempt.
Below is my code
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' => 'users',
],
/*
|--------------------------------------------------------------------------
| 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' => 'users',
],
'custom' =>[
'driver' => 'session',
'provider' => 'customusers'
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'custom_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\User::class,
],
'customusers' => [
'driver' => 'eloquent',
'model' => App\CustomUser::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| 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' => 60,
]
],
];
CustomUser.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class CustomUser extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guard = 'custom';
protected $table = 'customusers';
protected $fillable = [
'name', 'username', 'passcode',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'passcode', 'remember_token',
];
public function getAuthPassword()
{
return $this->passcode;
}
}
Route
Route::POST('/mlogin','Auth\LoginController#mLogin')->name('mylogin');
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
$this->middleware('guest:custom')->except('logout');
}
public function mLogin(Request $request){
echo $request->input('username').' '.$request->input('passcode');;
if (Auth::guard('custom')->attempt([
'username' => $request->input('username'),
'passcode' => $request->input('passcode')
])) {
echo 'success';
} else {
echo 'fail';
}
}
}
I am unable to login. what am i doing wrong here please guide.
If I am understanding it correctly you can try using the https://packalyst.com/packages/package/sboo/multiauth for multiple auth tables.
you should use custom guard when using Auth Methods.
so when attempting to authenticate users use this
Auth::guard('custom')->attempt()
I need to change the default User model in my Laravel Application to Admin model. I followed the tutorial given in change Authentication model in Laravel 5.3
the Admin model must do authentication, register and reset password. This is what I did so far.
After doing php artisan make:auth, I created Admin.php model
namespace Modules\Admin\Entities;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class Admin extends Authenticatable
{
use Notifiable;
protected $fillable = ['name','email','password'];
protected $hidden = [
'password', 'remember_token',
];
}
This is config/auth.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' => 'admins',
],
/*
|--------------------------------------------------------------------------
| 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' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'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' => \Modules\Admin\Entities\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| 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' => 'admins',
'table' => 'password_resets',
'expire' => 60,
],
],
];
and this is RegisterController.php
namespace App\Http\Controllers\Auth;
use Modules\Admin\Entities\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:admins'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return Admin::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
This code creates a user in admins table, but when I try to login, it throws the following error:
Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must be an instance of Illuminate\Contracts\Auth\UserProvider, null given, called in ...\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php on line 125
I can't understand why this error happens.
Change your code on config/auth.php:
'web' => [
'driver' => 'session',
'provider' => 'admins',
],
to:
'web' => [
'driver' => 'session',
'provider' => 'users',
],
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.
Change in your config/auth.php file like this:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
]
]
I develop site with laravel 5.2 and use
https://github.com/mcamara/laravel-localization and
http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/
i have followed everything in that link
my routes.php
Route::group([
'prefix' => LaravelLocalization::setLocale(),
'middleware' => ['web', 'localize', 'localeSessionRedirect', 'localizationRedirect']
], function () {
//Route::auth();
Route::get('login', 'UserAuthController#showLoginForm');
Route::post('login', 'UserAuthController#login');
Route::get('logout', 'UserAuthController#logout');
//user
Route::get('user/dashboard', ['as'=> 'user/dashboard', 'uses' => 'UsersController#index']);
});
Route::group(
['middleware' => 'web'], function () {
//Admin Login Routes...
Route::get('/admin/login','Admin\Auth\AuthController#showLoginForm');
Route::post('/admin/login','Admin\Auth\AuthController#login');
Route::get('/admin/logout','Admin\Auth\AuthController#logout');
Route::get('admin/dashboard', 'Admin\DashboardController#index');
Route::resource('admin/administrator', 'Admin\AdminController',['except' => 'show']);
UserAuthController.php
namespace App\Http\Controllers;
use Validator;
use Auth;
use Session;
use Illuminate\Http\Request;
use App\Http\Requests;
class UserAuthController extends Controller
{
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()){
// If validation falis redirect back to login.
return redirect('login')
->withErrors($validator)
->withInput();
}else {
$userdata = [
'email' => $request->email,
'password' => $request->password
];
// doing login.
if (Auth::guard('user')->validate($userdata)) {
if (Auth::guard('user')->attempt($userdata)) {
return redirect('/user/dashboard');
}
}
else {
// if any error send back with message.
Session::flash('error', 'Something went wrong');
return redirect('login');
}
}
}
public function logout()
{
Auth::guard('user')->logout();
return redirect('login');
}
}
UsersController.php
namespace App\Http\Controllers;
use Auth;
//use Session;
use App\User_Profile;
use Illuminate\Http\Request;
use App\Http\Requests;
class UsersController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
session()->put('uid',Auth::guard('user')->user()->id);
session()->put('username', Auth::guard('user')->user()->username);
session()->put('email', Auth::guard('user')->user()->email);
$uid = session()->get('uid');
$username = session()->get('username');
$profile = User_Profile::where('user_id', '=', $uid)->first();
return view('users.index', compact('username', 'profile'));
}
}
Admin\Auth\AuthController.php
namespace App\Http\Controllers\Admin\Auth;
use App\Admin;
use Validator;
use App\Http\Controllers\Admin\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
protected $redirectTo = 'admin/dashboard';
protected $guard = 'admin';
protected $redirectAfterLogout = 'admin/login';
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
}
my kernel.php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
// \Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
// 'auth' => [
// \App\Http\Middleware\Authenticate::class,
// \App\Http\Middleware\EncryptCookies::class,
// \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
// \Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
// ],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'localize' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
'localizationRedirect' => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
'localeSessionRedirect' => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
'user' => \App\Http\Middleware\RedirectIfNotUser::class,
];
}
config/auth.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' => 'user',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| 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' => [
'user' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| 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\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| Here you may set the options for resetting passwords including the view
| that is your password reset e-mail. You may also set the name of the
| table that maintains all of the reset tokens for your application.
|
| 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',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admin' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
I have success in admin logged in and do anything to manage backend
but not in user, everytime logged in when i refresh keep redirect back to login page. it seems $this->middleware('auth') not working.
Can you help me, where did i miss ?
Thank you
Be sure to have the forms in your views (the login-form, registration-form, ...) post to the localized url's.
So in your blade-views use:
<form method="POST" action="{{ url(LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(), '/password/email')) }}">
...
</form>
The above scripts are alright.
I made a mistake in the view, I placed
Signout
logout function in the navigation view.
I have changed the link with usual logout link.
Signout
Now its working.
thanks