I want to make auth with different table instead of default user table and I made with student table.
this is Student.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Student extends Authenticatable
{
use Notifiable;
protected $table='students';
protected $fillable=['full_name','email', 'password'];
protected $hidden = [
'password', 'remember_token',
];
public function getAuthPassword()
{
return $this->password;
}
}
auth.php
'defaults' => [
'guard' => 'web',
'passwords' => 'students',
],
'guards' => [
'students' => [
'driver' => 'eloquent',
'model' => App\Student::class,
],
//this is last
'students' => [
'provider' => 'students',
'table' => 'password_resets',
'expire' => 60,
],
],
'providers' => [
'students' => [
'driver' => 'eloquent',
'model' => App\Student::class,
],
],
'passwords' => [
'students' => [
'provider' => 'students',
'table' => 'password_resets',
'expire' => 60,
],
],
];
auth/RegisterController
<?php
namespace App\Http\Controllers\Auth;
use App\Student;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
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, [
'full_name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:students'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
$api_token=str_random(60);
return Student::create([
'full_name' => $data['name'],
'email' => $data['email'],
'api_token'=>$api_token,
'password'=>bcrypt($data['password']),
]
);
}
}
I can make register well but when I want to make login I am getting this error.
BadMethodCallException
Call to undefined method App\Student::generateToken()
From Laravel 5.7 l Helper 'str_random' became 'Str :: rondom'. and don't forget to be able to use the class "use Illuminate \ Support \ Str;"
Related
I have three tables.
1-customer
2-seller
3-affilate
I am fresher for LARAVEL, now i am studying on LARAVEL 8, so i wanted to make login with token api from these tables. Then how can i make please please please help me i am not able to find any proper solutions.
I have added in config/auth.php
'guards' => [
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
'affilate' => [
'driver' => 'session',
'provider' =>'affilate',
],
'customer' => [
'driver' => 'session',
'provider' => 'customer',
],
'seller' => [
'driver' => 'session',
'provider' => 'seller',
],
],
'providers' => [
'admin' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
'customer' => [
'driver' => 'eloquent','model'=>App\Models\Customer::class,
],
'seller' => [
'driver' => 'eloquent',
'model' =>App\Models\Seller::class,
],
'affilate' => [
'driver' => 'eloquent',
'model' =>App\Models\Affilate::class,
],
],
Here Is my First Models For Customer
<?php
namespace App\Models;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Customer extends Authenticatable
{
use HasFactory, HasApiTokens, Notifiable;
protected $table = 'customer';
protected $primaryKey = 'id';
protected $fillable = [
'name', 'email', 'mobile', 'countryCode','email_verified_at',
'email_verified','passWord','confirmPassword'
];
protected $hidden = [
'passWord', 'remember_token',
];
}
Controller For Customer
<?php
namespace App\Http\Controllers\API;
use Carbon\Carbon;
use App\Models\Customer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
class CustomerController extends Controller
{
public function customerLogin(Request $request)
{
if (Auth::guard('customer')->attempt($credentials))
{
$registerCustomer = Auth::Customer();
$token = $registerCustomer->createToken( $registerCustomer->name)->accessToken;
$success['success'] = true;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token->plainTextToken;
$success['tokenExpiryTime'] = 2592000000; //converted 30days minutes in miliseconds
$success['customerName'] = $registerCustomer->name;
return response()->json(['success' => $success ], $this->successStatus);
}else {
return response()->json(['error'=>'Unauthorised'], 401);
}
}
public function registerCustomer(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:55',
'email' => 'required|email|unique:customers',
'mobile' => 'required|digits:10|unique:customers',
'countryCode' => 'required|digits:6|unique:customers',
'passWord' => 'required|alpha_num|min:8',
'confirmPassword' => 'required|same:passWord|alpha_num|min:8',
]);
if($validator->fails())
{
return response()->json(['error'=>'Unprocessable Entity','validationErrors' => $validator->errors()], 422);
}
$customerData = array(
'name' => $request->name,
'email' => $request->email,
'mobile' => $request->mobile,
'countryCode' => $request->countryCode,
'passWord' => Hash::make($request->passWord),
'confirmPassword' => Hash::make($request->confirmPassword),
'email_verified' => '0',
'email_verified_at' => Carbon::now(),
);
$saveCustomerData = Customer::create($customerData);
return $this->customerLogin($request);
}
}
And Here Is My Routes
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\CustomerController;
Route::post('/customer/register', [CustomerController::class,
'registerCustomer']);
Route::post('/customer/login', [CustomerController::class,
'customerLogin']);
I wanted To Know Where is my mistake its Showing ErrorErrorException: Undefined variable $credentials in file
Thanks Please Please Please Please Please Please Help Me
try this manual method as you told attempt() is not working in your case
public function customerLogin(Request $request)
{
$customer = Customer::where('email', $request->email)->first();
if (!$customer) {
return response()->json(['error' => 'email not found'], 400);
}
if (Hash::check($request->email, $customer->password)) {
auth()->login($customer);
$registerCustomer = Auth::user();
$token = $registerCustomer->createToken($registerCustomer->name)->accessToken;
$success['success'] = true;
$success['message'] = "Success! you are logged in successfully";
$success['token'] = $token->plainTextToken;
$success['tokenExpiryTime'] = 2592000000; //converted 30days minutes in miliseconds
$success['customerName'] = $registerCustomer->name;
return response()->json(['success' => $success], $this->successStatus);
} else {
return response()->json(['error' => 'Unauthorised'], 401);
}
}
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
I have setup laravel and used it's default authentication controller but I modified the table name and it's table structure and accordingly I also changed the RegisterController and LoginController. And the RegisterController is working fine and registering a new user but when ever I try to login using the login form it gives the same validation error of "These credentials do not match our records."
I have attached the following files: LoginController, RegisterController, Admin(Model), Config->auth
I have overridden the username field according to my EmailAddress field.
Admin Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class admin extends Authenticatable
{
use Notifiable;
public $table = 'admin';
public $timestamps = false;
protected $primaryKey = 'AdminId';
protected $fillable = ['FirstName', 'LastName', 'FirstName_ar','LastName_ar','EmailAddress','Password','IsActive','remember_token'];
protected $hidden = ['Password', 'remember_token'];
public function getAuthPassword()
{
return $this->Password;
}
}
Login Controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Auth;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
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');
}
public function username()
{
return 'EmailAddress';
}
public function getRememberTokenName()
{
return "remember_token";
}
}
Register Controller
<?php
namespace App\Http\Controllers\Auth;
use App\admin;
use App\Http\Controllers\Controller;
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, [
'firstname' => 'required|string|max:255',
'lastname' => 'required|string|max:255',
'firstname_ar' => 'required|string|max:255',
'lastname_ar' => 'required|string|max:255',
'email' => 'required|string|email|max:255',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return admin::create([
'FirstName' => $data['firstname'],
'LastName' => $data['lastname'],
'FirstName_ar' => $data['firstname_ar'],
'LastName_ar' => $data['lastname_ar'],
'EmailAddress' => $data['email'],
'Password' => bcrypt($data['password']),
'IsActive' => 1,
'remember_token' => str_random(10)
]);
}
public function getRememberTokenName()
{
return $this->remember_token;
}
}
Config->auth.php
<?php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'admin',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'admin',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'admin' => [
'driver' => 'eloquent',
'model' => App\admin::class,
],
],
'passwords' => [
// 'users' => [
// 'provider' => 'users',
// 'table' => 'password_resets',
// 'expire' => 60,
// ],
'admin' => [
'provider' => 'admin',
'table' => 'password_resets',
'expire' => 60,
],
],
];
In the RegisterController, in the create method, instead of
'password' => bcrypt($data['password']), do this
'password' => Hash::make($data['password'])
Probably why your error is happening because maybe when you're registering you're using the bcrypt hashing method for the password but when you're logging, it's using a different hashing method.
Make sure to import the class
use Illuminate\Support\Facades\Hash;
at the top of your RegisterController file.
One more thing to take care of here is to make sure when you're inserting the new user record in the database, make sure to lowercase the email by default and when logging, make sure to lowercase the email too. Some databases are case sensitive by default. So you may have a problem there.
Like you have an email in the database,
Admin#example.com and when logging, you give admin#example.com, it will not match in that case.
Hope this helps.
i need to create three authentication: user, admin, restUser.
I managed to create multiple login for user and admin but when try to add login for restUser it returns user form...
this is my code:
app/Teretaneusers.php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Teretaneusers extends Authenticatable
{
use Notifiable;
protected $guard = 'teretaneuser';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
and I create table in MySQL database teretaneusers with column: name, email, password
config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'admin-api' => [
'driver' => 'token',
'provider' => 'admins',
],
'teretaneuser' => [
'driver' => 'session',
'provider' => 'teretaneusers',
],
'teretaneuser-api' => [
'driver' => 'token',
'provider' => 'teretaneusers',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Admins::class,
],
'teretaneusers' => [
'driver' => 'eloquent',
'model' => App\Teretaneusers::class,
],
],
Controllers/UserGymController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserGymController extends Controller
{
public function __construct()
{
$this->middleware('auth:teretaneuser');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('teretaneuser');
}
}
Controllers\Auth\UserGymLoginController.php
namespace App\Http\Controllers\Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
class UserGymLoginController extends Controller
{
public function __construct()
{
$this->middleware('guest:teretaneuser');
}
public function showLoginForm(){
return view('auth.teretaneuser-login');
}
public function login(Request $request){
//validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]
);
//attempt to log user in
if(Auth::guard('teretaneuser')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)){
return redirect()->intended(route('userGym.dashboard'));
}
return redirect()->back()->withInput($request->only('email','remember'));
}
}
auth/teretaneuser-login.blade.php
form class="form-horizontal" method="POST" action="{{
route('userGym.login.submit') }}"
and web.php
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::prefix('admin')->group( function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.dashboard');
});
Route::prefix('userGym')->group( function() {
Route::get('/login', 'Auth\UserGymLoginController#showLoginForm')->name('userGym.login');
Route::post('/login', 'Auth\UserGymLoginController#login')->name('userGym.login.submit');
Route::get('/', 'UserGymController#index')->name('userGym.dashboard');
});
Can somebody tell me where I'm wrong? When I try login from adress http://localhost/logovanje/public/userGym/login
it redirest me to http://localhost/logovanje/public/home
I use Laravel 5.4
I did the same for the admin and it worked.
Most likely you still have a valid session and you got a middleware (possibly RedirectIfAuthenticated) that is coming into play.
I think you could use Sentinel for this as it has an authentication package called roles and permissions
Here's a link for its documentation.
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',
]);
}