I generated a different table to store users for my website. Name of the table is tblusers. I am registering new users with a controller method register(), in which i added this code
public function register(){
return User::create([
'User_Email' => 'test#example.com',
'User_UserName' => 'test#example.com',
'User_Password' => bcrypt('123'),
'User_Address' => 'ABCD....',
'User_IsActive' => 1,
'User_FullName' => 'Burhan Ahmed',
'User_AppID' => 1,
'User_IsVerified' => 1
]);
}
It adds above dummy data successfully in Database. Then i tried to login with above given credentials using below code:
dd(Auth::attempt(['User_UserName' => 'test#example.com', 'User_Password' => '123']));
But above statement always returns false, Why? Am i missing something. I tried to pass actual bcrypt code instead '123' in above array it returns the same result always. Below is my Model Class
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
//class User extends Authenticatable
class User extends Authenticatable
{
use Notifiable;
protected $table = 'tblusers';
protected $primaryKey = 'User_ID';
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'User_UserName', 'User_Email', 'User_Password', 'User_Address', 'User_FullName', 'User_IsActive', 'User_IsVerified'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'User_Password'
];
}
I am using Laravel 5.4, i followed all the authentication steps but not matter what i pass it always return false.
if You want to Change the default table of login folow the steps
For Example You are Changing it to login_table
Step1:
change the table property in User.php (User Model)
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'login_table';
Step1:
IF YOU ARE BEGGINER
Now You need to change the table name users to login_table
IF PROJECT IS TEAM COLLBRATION MAKE THE MIGRATION WITH login_table
php artisan make:migration create_login_table_table
and add the columns available in the users table
Step3:
Now open the file app\Http\Controllers\Auth\RegisterController.php
You will find method validator as
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
Now You need to change unique:users to unique:login_table
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:login_table',
'password' => 'required|string|min:6|confirmed',
]);
}
Hope it helps and it works fine for me # Md.Sukel Ali
Comment if it not works
Related
I have this code in my controller:
$createAccreditorAccount = User::firstOrCreate(
['name' => "Accreditor"],
['nonofficial_category_id' => 0],
['role' => "accreditor"],
['email' => "accreditor#cvsucarmona.com"],
['password' => Hash::make('accreditor_cvsucarmona')],
['email_verified_at' => now()]
);
The error I get is this:
SQLSTATE[HY000]: General error: 1364 Field 'role' doesn't have a default value (SQL: insert into `users` (`name`, `nonofficial_category_id`, `updated_at`, `created_at`) values (Accreditor, 0, 2021-05-19 11:36:35, 2021-05-19 11:36:35))
Within the error display, it seems like the columns role, email and password do not fill my record.
I am pretty sure that I have included those columns in my $fillable.
Below is my User model:
<?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 User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'role',
'subcategory',
'email',
'password',
'nonofficial_category_id',
];
/**
* 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',
];
public function nonOfficialsCategories()
{
return $this->belongsTo(NonOfficialsCategories::class, 'nonofficial_category_id');
}
}
You don't need to specify each field value in it's own array and provide them as separate parameters, firstOrCreate() only takes 2 parameters, the first array is the unique fields to check against and the second param is the array of values to insert or update. It should be more like this...
$createAccreditorAccount = User::firstOrCreate(
[ 'email' => "accreditor#cvsucarmona.com" ],
[
'name' => "Accreditor",
'nonofficial_category_id' => 0,
'role' => "accreditor",
'email' => "accreditor#cvsucarmona.com",
'password' => Hash::make('accreditor_cvsucarmona'),
'email_verified_at' => now()
]
);
To explain why you are getting the error that you are, the firstOrCreate() method is checking ['name' => "Accreditor"] to see if it's unique and then attempting to insert ['nonofficial_category_id' => 0], which only has the nonofficial_category_id column set, hence the complaint about role not having a default value, ergo, you need to provide a value.
I am having some problems getting Laravel Sanctum authorising two tables in two separate databases.
I am using Laravel Sanctum tokens for authorisation. I have two tables to authorise users (users & contacts) I have setup two separate guards and can get everything to work on a single database with one token table.
However I want to have the contacts table in a separate database. Doing so creates two personal_access_tokens tables, one in the Users database and the other in the Contacts database, which I don't mind. I can create the tokens just fine, however when I try to authorise contacts using a token, Sanctum is trying to look in the Users personal_access_tokens table, not the Contacts personal_access_tokens table. So essentially it's just looking at the wrong database for the personal_access_tokens table and I don't know how to change that.
My setup is as follows:
Guards:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
/*'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],*/
'users' => [
'driver' => 'sanctum',
'provider' => 'users',
'hash' => false,
],
'contacts' => [
'driver' => 'sanctum',
'provider' => 'contacts',
'hash' => false,
],
],
Providers
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'contacts' => [
'driver' => 'eloquent',
'model' => App\Models\Contact::class,
],
],
User Model
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;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* 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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Contact Model
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;
use Laravel\Sanctum\HasApiTokens;
class Contact extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The connection name for the model.
*
* #var string
*/
protected $connection = 'puranet_crm';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
];
/**
* 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',
];
}
My two api routes for autorisation are:
Route::group(['middleware' => 'auth:sanctum'], function() {
//All secure URL's
Route::get('test',[UserController::class, 'test']);
});
Route::group(['middleware' => 'auth:contacts'], function() {
Route::get('test-contacts',[ContactController::class, 'test']);
});
Contact Controller (this is identical to the UserController with exception to the Model it is referencing)
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Contact;
use Illuminate\Support\Facades\Hash;
class ContactController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
*/
public function login(Request $request)
{
$user = Contact::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
return response([
'message' => ['These credentials do not match our records.']
], 404);
}
$token = $user->createToken('contacts-app-token')->plainTextToken;
$response = [
'user' => $user,
'token' => $token
];
return response($response, 201);
}
/**
* #return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
*/
public function test()
{
return response(["response" => "Test Contacts"], 201);
}
}
You need to overwrite the sanctum model on your project and overwrite the $connection variable inside of it, so you will be able to connect to the database that you would like to, same when you do with normal Models.You can find how to overwrite sanctum model on the Laravel documentation for version 8.
Create a this model in one of your projects to overwrite where sanctum will look for the token.
class PersonalAccessToken extends SanctumPersonalAccessToken{
use HasFactory;
protected $connection = 'name of your connection in database.php';
}
So both sanctum will use the same DB to auth the User.
I hope I helped you :)
I have a problem with inserting rows in Laravel.
Theory: I use simple Laravel authentication and have two tables.
users: id, name, password.
user_details: id, userID, email
After the registration it would be useful to insert rows into both tables, and the userID = id (in users table).
RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
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, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'e_r' => $data['e_r'],
]);
$details = UserDetails::create([
'firstname' => 'joco',
'lastname' => 'nagy',
'email' =>$data['email'],
'position' => 'cleaner',
'salary' => '250000',
'amount_holiday' => '40'
]);
return $user;
}
}
(I have just tried to insert fake datas. There are default values in migration files.)
Models:
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'e_r',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function user_detail(){
return $this->hasOne("App\UserDetails");
}
}
Error:
FatalThrowableError in RegisterController.php line 74: Class
'App\Http\Controllers\Auth\UserDetails' not found
I do not understand why should be my model in Auth directory.
Have you include your model UserDetails?
Include it on top:
use App\User;
use App\UserDetails;
or
Change UserDetails to App\UserDetails.
$details = App\UserDetails::create([
'firstname' => 'joco',
'lastname' => 'nagy',
'email' =>$data['email'],
'position' => 'cleaner',
'salary' => '250000',
'amount_holiday' => '40'
]);
You should use use statement eg. use Your\Name\Space\UserDetails;
Without this declaration PHP is looking for UserDetails class in your current namespace, in your case App\Http\Controllers\Auth. That's why you get
'App\Http\Controllers\Auth\UserDetails' not found
I'm working with an old copy of a client's database and making the new Laravel app work with its existing users.
I was building and testing with my User model using the 'users' table, but I'm trying to hook it up to the 'auth_user' table. After the changes, my new users are being created correctly. The login is a problem though. The users are passing Auth::attempt($credentials) as expected, but failing when
In my LoginController...
// post to /login
public function login() {
$input = Request::all();
// Log the user in
if (Auth::attempt(['email'=>$input['username'], 'password'=>$input['password']])) {//Auth::attempt(Auth::attempt("admin", ['email' => $input['username'], 'password' => $input['password'], 'active' => 1])) {
// the user is now authenticated.
return Redirect::to('/welcome')->with('message', 'Successfully authenticated');
}
return Redirect::to('/')
->with('message', 'Login Failed: Your Login Credentials Are Invalid');
}
}
I'm definitely passing the Auth::attempt(...), but I don't think my session is being set for that user. After the redirect to /welcome, I fail the Auth::check('user')
public function welcome() {
if (!Auth::check('user')) return Redirect::to('/');
// ... Top secret stuff (no returns or redirects though)
return view('user.welcome', [
'user' => Auth::user()
// ...
]);
}
This redirects back to my login controller.
The kicker is this was all working when I was using my 'users' table instead of 'auth_user'.
Users uses id as the primary key, Auth_user uses 'uid' as the primary key. I'd love to change the uid to be id, but I have to reuse a scary number of MYSQL stored procedures that I can't change.
Relevant models:
User.php:
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
public function rules($scenario = null, $id = null) {
$rules = [];
switch($scenario) {
case 'userAdd':
$rules = [
'password' => 'required|confirmed|min:6'
];
break;
case 'passwordChange':
$rules = [
'password' => 'required|confirmed|min:6'
];
break;
}
return $rules;
}
public function isValid($scenario = null) {
$validation = User::make($this->attributes, User::rules($scenario));
if($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'auth_user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['username', 'name', 'password', 'email', 'expire', 'active', 'organization','role'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
protected $primaryKey = 'uid';
}
Auth.php (for multiple user types -- I know, I'd rather use roles instead of separate models too)
<?php
return [
'multi' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
'table' => 'auth_user'
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
'table' => 'auth_admin'
]
],
];
I think I covered all my bases for the primary key change, but I can't get the model to pass Auth::check(). Can someone with more Laravel experience illuminate what I'm doing wrong? Thanks in advance!
This is not a complete fix. I still can't find anything to tell Laravel/Guard not to look at the ID column, so I bandaided it by adding an ID column and $user->id = $user->uid;. I'm not proud of this, but it works.
In your User.php Script you need to place this code and this code make the table to login check.
protected $table='auth_users';
In your User.php code place that protected table code in initial stage( after the class function).
I am pretty new to laravel and having some difficulty with the authorization process. I have recreated an empty users table in mysql using php artisan migrate:refresh. When I go to the registration page fill out the fields and hit register, my table in mysql does not get updated. I am redirected to the correct weblink I set, so that part seems to be working.
I have made sure that mysql is connected to my laravel project, so the connection isn't the problem.
Below is the code in the AuthController.php. The views for register and login were made with the php artisan make:auth command.
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',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
Below is the code in my User.php file which is in the app directory.
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Users extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
In order to use create you need to specify in User model $fillable array
protected $fillable = [
'email',
'password',
'name',
];
OR $protected (so value want update)
Read more Docs