Can I change Model User that used in auth system in laravel? - laravel

I tried to change User Model that used by default when use command php artisan ui:auth
to another model
but all of way to do that is not working
What should to do that ?
I am using laravel version 7.x

You can have different (or as many different) models as you want for various reasons. You just need to change the relevant section in config/auth.php. I always use a Models directory, so one of the first things I do with a new app is to relocate the User model and then tell Auth where to look for it:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
You also have to update the model's use statements in your controllers if you have custom logic, but for a vanilla Laravel Auth set-up, you should be good just by changing the config.
Edit: If you do have a structure like mine (a models directory) the default App\User namespace declaration has to change on the model itself:
Change:
namespace App;
To:
namespace App\Models;
Or whatever it is that matches your structure.

Related

Routes missing for Laravel Backpack admin

We have several Laravel applications that use Backpack for the admin panel. A developer wrote a package that used Single sign-on. We have removed this package as it was not working correctly. Once Composer was used to updating Laravel and remove the package, there are NO routes to deal with admin login. Our applications use Laravel 5.8/6 and Backpack 3.6/4.0.
I created another test application with Laravel 5.8 using Backpack 3.6, and the routes are available for login. As you can see, all the login routes are available.
If you look at the following image, you can see the login routes are all missing.
Is there a way to add the routes in again? Laravel Backpack is still installed, but I need to re-register the routes.
All the settings in the application are set to default. I have even made the default authentication guard in config/auth.php to Backpack.
config/auth.php
'defaults' => [
'guard' => 'backpack',
'passwords' => 'users',
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
],
config/backpack/base.php
'route_prefix' => 'admin',
'setup_auth_routes' => false,
'setup_dashboard_routes' => true,
'setup_my_account_routes' => true,
'user_model_fqn' => App\Models\BackpackUser::class,
'middleware_class' => [
App\Http\Middleware\CheckIfAdmin::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
// \Backpack\Base\app\Http\Middleware\UseBackpackAuthGuardInsteadOfDefaultAuthGuard::class,
],
// Alias for that middleware
'middleware_key' => 'admin',
'authentication_column' => 'email',
'authentication_column_name' => 'Email',
'guard' => 'backpack',
'passwords' => 'backpack',
config/backpack/permissionmanager.php
'models' => [
'user' => App\Models\BackpackUser::class,
'permission' => Backpack\PermissionManager\app\Models\Permission::class,
'role' => Backpack\PermissionManager\app\Models\Role::class,
],
'allow_permission_create' => false,
'allow_permission_update' => false,
'allow_permission_delete' => false,
'allow_role_create' => true,
'allow_role_update' => true,
'allow_role_delete' => true,
'multiple_guards' => true,
app/Models/BackpackUser.php
class BackpackUser extends User
{
use CrudTrait;
use HasRoles;
use InheritsRelationsFromParentModel;
protected $table = 'users';
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
public function getEmailForPasswordReset()
{
return $this->email;
}
}
So pretty much standard settings. I cannot figure out why the routes are not registered and available. If you get to http://localhost/admin, I get redirected to http://localhost/admin/login, which gives a 404 error. Can anyone help?
You have to enable 'setup_auth_routes' => true in config/base.php. This will allow Backpack to use the standard routes. Then the second step is to use Auth::routes(); inside your routes/web.php
If you are missing some/all of the controllers or UIs then you can scaffold them:
Install laravel/ui part using composer require laravel/ui
Use php artisan ui vue --auth or php artisan ui bootstrap --auth or php artisan ui react --auth depending on what you use for the front-end.

Mapping different column and table names for Laravel Authentication without re-writing all of the auth classes

We store our authentication information in a different table and column names than Laravel uses by default. It's still stored in MySQL. When doing research, in the documentation it says that we have to write completely different authentication handlers.
Is there really not any way to just remap the table and column names in a central place?
If not is there a better way to handle this? Should we just create a new table using the authentication information?
You can change your table/model name for authentication purposes inside the config\auth.php file.
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
Now, when it comes to changing column name by default Laravel using email field which you can change by putting a function username() which will return the field to be used for authentication inside LoginController.php.
public function username()
{
return 'username';
}
Hopefully this helps.
The Model associated with the login process can be modified in:
config/auth.php
under the 'providers' section:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\Models\MyOwnUsersTable::class,
],
],
However, the login process is a bit more tricky. the LoginController uses the AuthenticatesUsers trait, where you may override the required methods. For example the login method
class LoginController extends Controller
{
use AuthenticatesUsers;
public function login(Request $request)
{
//Do whatever you have to do
return $this->sendLoginResponse($request);
}
}
So, basically, I encourage you to study the
Illuminate\Foundation\Auth\AuthenticatesUsers
and reuse as much as possible from that class, and only override the methods you need to.

Laravel 6.5.2 error when registering on overwritten users table

I have overwritten the default user table with an existing table.
When trying to register a new user i get the following error:
Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\customUser given, called in {path}\vendor\laravel\framework\src\Illuminate\Foundation\Auth\RegistersUsers.php on line 35
To overwrite the default users table with my own I have made the following changes:
///Auth.php///
//Auth defaults:
'defaults' => [
'guard' => 'web',
'passwords' => 'customusers',
],
//Auth guards:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'customusers',
],
//User providers:
'providers' => [
'customusers' => [
'driver' => 'eloquent',
'model' => App\customUser::class,
],
I don't know if these changes could cause the error I'm facing.
The error is supposedly fired in this part of 'RegisterUsers.php'
$this->guard()->login($user);
This is part of the function 'register', which looks like this:
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
Any help regarding this error would be kindly appreciated, I'm fairly new to Laravel so I would like to recieve a clear explanation to my problem so I can understand why it is calling this error.
Kind regards,
geertjanknapen
Your model needs to extend Illuminate\Foundation\Auth\User, otherwise you cannot use it with the authentication methods like login / logout etc.
In your customUser model add the following:
use Illuminate\Foundation\Auth\User as Authenticatable;
class customUser extends Authenticatable
I would also recommend to rename your class customUser to CustomUser in order to follow PSR-1:
Class names MUST be declared in StudlyCaps.
The term ‘StudlyCaps’ in PSR-1 MUST be interpreted as PascalCase where
the first letter of each word is capitalized including the very first
letter.
On RegisterUsers.php you need to include
use Illuminate\Foundation\Auth\AuthenticatesUsers;
and below class RegisterUsers extends Controller
you need to add
use AuthenticatesUsers;

"Class 'App\Game\User' not found" even with changed providers

When i try to register an account it comes up with this error " class App\Game\user" not found
I have changed the providers auth.php to App\Game\User::class,
and i have changed the name space on the user.php to namespace App\Game;
Game.php does exist (however nothing is coded in it and im wondering if this is the problem?)
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Game\User::class,
],
the browser highlights the return line in this part of the RegisterController
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Edit: I didn't realize it meant folders in the naming convention and put them into the appropriate folders. Thank you. My apologies i couldn't find a question relating to this on stackover flow and ive only just started on laravel
First of all if you have something like App\Game\User::Class
That means you will have a game folder inside the app folder and then user.php file in that Game folder with. You can use the full namespace to call the class like \App\Game\User if it's still not working try to run composer dump-autoload to regenerate the composer files.
Laravel model stores under app>user.php and make sure your file does exist in app>game folder

how to create multi auth in one single login form

I want to create an authentication system (one single form) that gives the ability to admin and student to access tow different interfaces the admin can access the control panel and the user access the main system. in addition, I want separate tables in the database one for the admin and the other for the student. is there a possible way to do this? any suggestions please and how to do it.
Thank you...
You need to change redirectifauthenticated.php file in middleware folder.
I can edit my answer later, i can't access my codes right now. But this idea will work:
In the handle function:
switch ($guard){
case 'admin':
if (Auth::guard($guard)->check()){
//if you are using some role package, use with auth()->user()->hasrole('admin'), depends //your package
return redirect()->route('adminurl');
}
break;
default:
if (Auth::guard($guard)->check()){
return redirect('/homepage');
}
break;
}
return $next($request);
In config/auth.php also you need to add admin guard to the guards section. Also same thing for providers.
this for providers:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\AdminModel::class,
],
]

Resources