Using different Table for Authentication in Laravel - php

I tried with the default user table for Laravel Auth purpose,
Now i am changing it to the admin Table
So i refereed here
Accordingly i tried to change the Table name as admin in the auth.php
'model' => 'User',
'table' => 'users',
to
'model' => 'AdminModel',
'table' => 'admin',
And in the AdminModel i have protected $table = 'admin';
And i got the error
Class AdminModel contains 6 abstract methods and must therefore be declared abstract or implement the remaining methods (Illuminate\Auth\UserInterface::getAuthIdentifier, Illuminate\Auth\UserInterface::getAuthPassword, Illuminate\Auth\UserInterface::getRememberToken, ...)
Is there anything is should change rather than here ?
Here is my AdminModel :
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class AdminModel extends Eloquent implements UserInterface, RemindableInterface
{
protected $table = 'admin';
protected $fillable = array('UserName', 'Password');
public $timestamps = true;
public static $rules = array();
}
Update :
I replaced with appropriate changes
i.e.,
use UserTrait, RemindableTrait;
Solved,
It didn't ended in success
I checked
if (Auth::attempt(array('UserName' => $UserName, 'password' => $password)))
{
return Redirect::intended('dashboard');
}
else
{
$queries = DB::getQueryLog();
print_r(end($queries));
}
And it is always printing the query like this
Array ( [query] => select * from `admin` where `UserName` = ? limit 1 [bindings] => Array ( [0] => a ) [time] => 1 )
What might be the issue ?

Related

Laravel Auth Attempt not working with Custom User Model

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

Laravel 5 Unit Test - Call to a member function connection() on null

I tried creating a unit test for the relationships between my User and Shop models, however when I run vendor\\bin\\phpunit this error(s) are thrown, I have no idea about this since I'm a newbie in unit testing. I tried to run my code on my controller to see if the relationship actually works, and fortunately it is working as expected, but not when run in phpunit. What have I done wrong for this phpunit not to work with Models?
Fatal error: Uncaught Error: Call to a member function connection() on null in E:\projects\try\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php:1013
Stack trace:
E:\projects\try\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(979): Illuminate\Database\Eloquent\Model::resolveConnection(NULL)
This is my UserTest.php
<?php
namespace Tests\Unit;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\User;
use App\Shop;
class UserTest extends TestCase
{
protected $user, $shop;
function __construct()
{
$this->setUp();
}
function setUp()
{
$user = new User([
'id' => 1,
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'JohnDoe#example.com',
'password' => 'secret',
'facebook_id' => null,
'type' => 'customer',
'confirmation_code' => null,
'newsletter_subscription' => 0,
'last_online' => null,
'telephone' => null,
'mobile' => null,
'social_security_id' => null,
'address_1' => null,
'address_2' => null,
'city' => null,
'zip_code' => null,
'signed_agreement' => 0,
'is_email_confirmed' => 0
]);
$user = User::find(1);
$shop = new Shop([
'id' => 1,
'user_id' => $user->id,
'name' => 'PureFoods Hotdog2',
'description' => 'Something that describes this shop',
'url' => null,
'currency' => 'USD'
]);
$user->shops()->save($shop);
$shop = new Shop([
'id' => 2,
'user_id' => $user->id,
'name' => 'PureFoods Hotdog',
'description' => 'Something that describes this shop',
'url' => null,
'currency' => 'USD'
]);
$user->shops()->save($shop);
$this->user = $user;
}
/** #test */
public function a_user_has_an_id(){
$user = User::find(1);
$this->assertEquals(1, $user->id);
}
/** #test */
public function a_user_has_a_first_name()
{
$this->assertEquals("John", $this->user->first_name);
}
/** #test */
public function a_user_can_own_multiple_shops()
{
$shops = User::find(1)->shops()->get();
var_dump($this->shops);
$this->assertCount(2, $shops);
}
}
It seems, this error is caused by this line of code:
$user->shops()->save($shop); - this code actually works when run in my sample routes or Controller but is throwing errors when run in phpunit
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $guarded = [ 'id' ];
protected $table = "users";
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* returns the Shops that this user owned
*/
public function shops()
{
return $this->hasMany('App\Shop');
}
}
Shop.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shop extends Model
{
protected $guarded = [ 'id' ];
protected $table = "shops";
/**
* returns the Owner of this Shop
*/
public function owner()
{
return $this->belongsTo('App\User');
}
}
Any help will be very much appreciated. Thanks!
First of all, setUp() is called before every test, so you shouldn't call it from within the constructor
Second of all, you should call the parent::setUp() in your setUp() to initialize the app instance.
One more reason
check if the test class is extending use Tests\TestCase; rather then use PHPUnit\Framework\TestCase;
Laravel ships with the later, but Tests\TestCase class take care of setting up the application, otherwise models wont be able to communicate with the database if they are extending PHPunit\Framework\TestCase.
Example:
<?php
class ExampleTest extends TestCase
{
private $user;
public function setUp()
{
parent::setUp();
$this->user = \App\User::first();
}
public function testExample()
{
$this->assertEquals('victor#castrocontreras.com', $this->user->email);
}
}
a solution
use PHPunit\Framework\TestCase
Put this
use Tests\TestCase
You are assigning the id '2' to both shops.
Assigning is should not be neccessary since I assume the shop table id field is an autoincrement field.
Also look into database factories in the Laravel docs, it will simplify things for you.
That can be happens when you try to read database from dataprovider function. Like me tried, yes. The work way:
protected static $tariffs_default;
protected function setUp(): void {
parent::setUp ();
if (!static::$tariffs_default){
static::$tariffs_default = DB::...;
}
}
// in dataprovider we use string parm, named as our static vars
public static function provider_prov2(){
return [
[".....", [ 'tariffs'=>'tariffs_default'] ],
];
}
// then, in test we can ask our data by code:
public function testSome(string $inn, string $ogrn, $resp_body){
if ( $ta_var = Arr::get( $resp_body, 'tariffs' ) ){
Arr::set($resp_body, 'tariffs', static::$$ta_var );
}
$this->assert...
}
Cause of the problem: you can't use Laravel Models functionality from code called in the constructor of Class UserTest - even though you put the code in the method "setUp", you unnecessarily called it from the constructor. SetUp is called by phpUnit without you needing to do it in the constructor.
When the UserTest constructor has run, the Laravel Bootstrap code has not yet been called.
When the UserTest->setUp() method is called, the Laravel Bootstrap code HAS been run, so you can use you Models etc.
class UserTest extends TestCase
{protected $user, $shop;
function __construct()
{
$this->setUp(); // **THIS IS THE PROBLEM LINE**
}
function setUp()
{
$user = new User([....
Try composer dump-autoload
~Regards

Saving to relational table Laravel 4

Basically I have a groups table with id and name,
I have another table with users_groups with id, group_id and user_id
I'm try to save when a user is created to the users_groups table, but when I use this code it saves what it can in the groups table. Is there something I'm doing wrong?
Account controller (saving user to db and set group to id 1)
$user = User::create(array(
'firstName' => $firstName,
'lastName' => $lastName,
'dateOfBirth' => $dateOfBirth,
'gender' => $gender,
'email' => $email,
'username' => $username,
'password' => Hash::make($password),
'code' => $code,
'active' => 0
));
Group::create([
'user_id' => $user->id,
'group_id' => '1' //1 is not assigned
]);
Group Model
class Group extends Eloquent
{
protected $fillable = array('name');
// DEFINE RELATIONSHIPS --------------------------------------------------
// define a many to many relationship
// also call the linking table
public function users() {
return $this->belongsToMany('User', 'users_groups', 'group_id', 'user_id');
}
}
User Model
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable =array('email', 'username', 'password', 'password_temp', 'code', 'active', 'firstName','lastName','gender','dateOfBirth');
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
// Each User BELONGS to many Groups
// Define our pivot table also
public function groups() {
return $this->belongsToMany('Group', 'users_groups', 'user_id', 'group_id');
}
}
All information about saving relations can be found here
You need attach()
$user = User::create(array(
'firstName' => $firstName,
// ...
));
$user->groups()->attach(1); // 1 being the group_id

Laravel Auth Issue while using different table name

This Questions is the continuation of this
I tried with the default user table for Laravel Auth purpose,
Now i am changing it to the admin Table
So i refereed here
Accordingly i tried to change the Table name as admin in the auth.php
'model' => 'User',
'table' => 'users',
to
'model' => 'AdminModel',
'table' => 'admin',
And in the AdminModel i have protected $table = 'admin';
Here is my AdminModel :
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class AdminModel extends Eloquent implements UserInterface, RemindableInterface
{
protected $table = 'admin';
protected $fillable = array('UserName', 'Password');
public $timestamps = true;
public static $rules = array();
}
Here is my Controller :
if (Auth::attempt(array('UserName' => $UserName, 'password' => $password)))
{
return Redirect::intended('dashboard');
}
else
{
$queries = DB::getQueryLog();
print_r(end($queries));
}
And it is always printing the query like this
Array ( [query] => select * from `admin` where `UserName` = ? limit 1 [bindings] => Array ( [0] => a ) [time] => 1 )
What might be the issue ?

How to disable 'create_at' and 'update_at' in Laravel's seed file?

I don't want to use rows 'update_at' and 'create_at', but Laravel's seed file is trying to update it. How can I disable it?
Here is the code that I'm using:
use Illuminate\Database\Migrations\Migration;
class SeedUsersTable extends Seeder {
// $timestamps = false; <=== will return error
// public static $timestamps = false; <=== will return error
public function run()
{
DB::table('users')->delete();
User::create(array(
'id' => 1,
'name' => 'Админ',
'password' => Hash::make('admin'),
'login' => 'admin'
));
}
}
According to the Laravel docs,
... by default, Eloquent will maintain the created_at and updated_at columns on your database table automatically. Simply add these timestamp columns to your table and Eloquent will take care of the rest.
If you do not wish for Eloquent to maintain these columns, In your User model add the following:
class User extends Eloquent {
public $timestamps = false;
}
use Illuminate\Database\Migrations\Migration;
class SeedUsersTable extends Seeder {
public function run()
{
DB::table('users')->delete();
$user = new User(array(
'id' => 1,
'name' => 'Админ',
'password' => Hash::make('admin'),
'login' => 'admin'
));
$user->timestamps = false;
$user->save();
}
}

Categories