Laravel 5.3 Change user table in Auth - laravel

I'm using Laravel 5.3 and used the make:auth artisan command to scaffold the login/registration system. I'm doing my login as companies, so I have a table called Company. How do I change the original sql to go get the email and password from the Company table instead of the User table?
I already tried to change in the config/auth.php file in the providers part, but when I changed 'model' => App\User::class, to 'model' => App\Company::class,, it started logging in, but regardless if the email and password input were completely wrong. Any ideas?
EDIT: After the Company registers and logs in, it has the ability to invite Users, therefore the original User table has to remain

Laravel 5.3 has changes in the Auth implementation. For me, this way solved it:
First, provide a company table in the database that fulfils the criteria to be used for identification. Thus, it needs a name, email, password and remember_token column. Details can be found here.
In the config/auth.php change the users model to your company class.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Company::class,
],
Create a Company class in the App folder that extends the Auth, so use:
use Illuminate\Foundation\Auth\User as Authenticatable;
In the Company class, define fillable and hidden fields.
class Company extends Authenticatable {
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
}
In the RegisterController.php change "use App\User" to
use App\Company;
Adjust the create and validator function in the RegisterController.php with Company::create
protected function create(array $data)
{
return Company::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:companies',
'password' => 'required|min:6|confirmed',
]);
}
'email' => 'required|email|max:255|unique:companies'
(table name for Company Model will be companies)
Hope this helps!

DO NOT FORGET TO CHANGE VALIDATION IN REGISTERCONTOLLER.PHP AS WELL.
from
'email' => 'required|email|max:255|unique:users',
to
'email' => 'required|email|max:255|unique:company',

Related

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

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

Creation of related Models on auth RegisterController in laravel

In my application, I have tables related to users and some of these tables require a row be inserted as soon as a User is registered.
For example, I have the following models:
UserProfile,
UserAssignedRole,
UserSettings
As soon as a User successfully registers, they will need a corresponding row in the DB.
I've done the following:
protected function create(array $data)
{
$user = User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
UserProfile::create([
'user_id' => $user->id,
]);
UserAssignedRole::create([
'user_id' => $user->id,
'role_id' => 1
]);
UserSettings::create([
'user_id' => $user->id,
'nsfw' => 1
]);
return $user;
}
I'm looking for a better and more elegant way to achieve this. Is there a "Laravel" way in achieving this?
In the Larvel docs there's a chapter about Recursively Saving Models & Relationships. This is probably what you're looking for. They specify the following example:
$post = App\Post::find(1);
$post->comments[0]->message = 'Message';
$post->comments[0]->author->name = 'Author Name';
$post->push();
You could achieve something similar by creating a user including all its relationships in one push().

Change table users in laravel 5.5

I've created a new table called "admins" table. I want to use this instead of the users table.
I've already added this in my User model:
protected $table = 'admins';
And I also tried this on my auth.php:
'users' => [
'driver' => 'database',
'table' => 'admins',
],
But none of them worked. Are there any other solutions that could work?
For one, you must also change the RegisterController, in it you will find the create method:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
As you can see it too uses the User model.

Laravel Passport Register the user credentials were incorrect

I set up Laravel Passport and currently I am trying to register user with a Post Route. I did create a RegisterController inside Controllers/Api/Auth.
Thus I created a clients table which looks excatly like a users table.
The client gets created if I call the route, but I do not get an access token nor a refresh token.
The route to my controller looks like this (routes/api):
Route::post('register', ['as' => 'register', 'uses' => 'Api\Auth\RegisterController#register']);
My Controller looks like this:
<?php
namespace App\Http\Controllers\Api\Auth;
use App\Client;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Route;
use Laravel\Passport\Client as PClient;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
private $client;
public function __construct() {
$this->client = PClient::find(1);
}
public function register(Request $request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email',
'password' => 'required|min:6|confirmed'
]);
$client_user = Client::create([
'name' => request('name'),
'email' => request('email'),
'password' => bcrypt(request('password'))
]);
$params = [
'grant_type' => 'password',
'client_id' => $this->client->id,
'client_secret' => $this->client->secret,
'username' => request('email'),
'password' => request('password'),
'scope' => '*'
];
$request->request->add($params);
$proxy = Request::create('oauth/token', 'POST');
return Route::dispatch($proxy);
}
}
This is my Client Model:
class Client extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword, HasApiTokens, Notifiable;
protected $table = 'clients';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
When I am trying to call it with Postman I get this error message:
I may be way off basis here but it looks as if you are creating your client with a password of "password" due to your bcrypt('password') call.
Should it not be bcrypt(request('password'))?
This would explain why your credentials are wrong in your request, because they are ; )
Ok I fixed it, the post route worked if I used the User Model instead of my Client model, so I guessed that there has to be something different.
After some research I have found out that one needs to add the model, in my case the client model to the providers array inside config/auth.php.
So first one needs to change the api guard like this:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'clients',
],
],
This way to api routes login and register only take action with my clients.
Now you need to a a new provider in this case a clients provider like this.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'clients' => [
'driver' => 'eloquent',
'model' => App\Client::class
],
],
And voila I get an access token + refresh token if I call the route.

laravel 5.4 change authentication users table name

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

Resources