i use this package :
https://github.com/spatie/laravel-permission/tree/v2
code :
$user=User::find(2);
$user->assignRole('admin');
and when i assign admin role to user I'm dealing with this error
There is no role named admin.Spatie\Permission\Exceptions\RoleDoesNotExist
this is my default guard in auth.php :
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
this is my roles table :
this is my role_has_permission table
and this is my permission table :
just add this protected property to your user model(or whatever model you are using for assigning permissions and roles).
protected $guard_name = 'api';
Add one of the following to your User model:
public $guard_name = 'api';
Or:
public function guardName()
{
return 'api';
}
As a convention it's best to do configurable things in the config file.
The problem with your code is the order of arranging your guards, just re-arrange as seen below.
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
...
Once this is done, you don’t need to add protected $guard_name = 'api'; to your User model, ensure to run php artisan config:clear
Ref: Saptie Laravel Permisions
friends! I found solution for this problem but first of all, i illustrate why this problem happened. As you know, Laravel read the codes from top to bottom and from left to right. Moreover when we want from laravel fresh all data by command
php artisan migrate :fresh --seed
It clears all this data and the problem begin. By other word, when assign Role command to check for new role it fails because all data is cleared before it access to those data. To avoid this we should set Role seeder class before Admin seeder class in database seeder
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call([RoleSeeder::class, AdminSeeder::class]);
}
}
Add this to your user model
use Spatie\Permission\Traits\HasRoles;
and in a user model class
use HasRoles;
Here is a reference
Complete example
This worked for me:
$role = Role::create(['guard_name' => 'admin', 'name' => 'manager']);
Related
This is how my config/auth.php looks like.
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'jwt',
'provider' => 'admins',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'provider' => App\Models\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
And this is how I defined the guard in my controller:
if (! $token = JWTAuth::attempt($credentials,['guard' => 'admin'])) {
return response()->json(['error' => 'invalid_credentials'], 400);
}
Problem is I have customized admin guard and defined the model that I wanna use but It's looking for default guard and when it does it avoids the custom guard and use default guards providers User model(Which I want to avoid) . To get rid of it I removed the default api guard and now it's saying api guard not defined. If I define I only can use one guard and can't use my customize guard. How can I avoid the default guard and use other two guard ?
In admin controller,
public function __construct(){
\Config::set('auth.defaults.guard','admin');
}
In manager controller,
public function __construct(){
\Config::set('auth.defaults.guard','manager');
}
This solved the problem!
Define a new guard in the guards array of the config/auth.php file. For example, you can add a custom guard like this:
'guards' => [
// ...
'custom' => [
'driver' => 'session',
'provider' => 'users',
],
],
Define a new provider in the providers array of the config/auth.php file. This provider should be responsible for retrieving and authenticating your users. For example, you can add a custom provider like this:
'providers' => [
// ...
'custom' => [
'driver' => 'eloquent',
'model' => App\Models\CustomUser::class,
],
],
Create a new middleware that sets the guard for your custom authentication. For example, you can create a CustomAuthenticate middleware like this:
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate;
class CustomAuthenticate extends Authenticate
{
protected function authenticate($request, array $guards)
{
if (!empty($guards) && $guards[0] === 'custom') {
return auth()->guard('custom')->check();
}
parent::authenticate($request, $guards);
}
}
Apply the new middleware to your routes or controllers. For example, you can add the CustomAuthenticate middleware to your routes like this:
Route::middleware(['auth:custom'])->get('/custom', function () {
return view('custom');
});
or alternatively you can define the guard that you want only to be used within the controller by setting this in your construct method.
public function __construct()
{
$this->middleware('auth:custom');
}
To set the users guard upon logging in you can do within your login post request within your Login controller.
if (Auth::guard('custom')->attempt($credentials)) {
// Authentication passed...
return redirect()->intended('dashboard');
}
When youre logging in to set the guard with JWTAuth you can do;
$token = JWTAuth::guard('custom')->attempt($credentials);
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 got a file called
AuthServiceProvider.php
in the Providers directory in Laravel project.
I actually don't understand about how it works and why it's needed
Can anyone explain with details?
Thanks in advance.
AuthServiceProvider is the default guard that Laravel uses to give the service authentication in the system. But if you need you can make your own guards for specific situations, in that case you will have you own AuthServiceProvider.
For eg. In one system that we made, the customer had his own database with it's specific users table, we can't use the default Laraver AuthServiceProvider. Because the table have other fields. So we created our CustomAuthProvider. It's complex, but you need to declare the driver en config/auth.php
...
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
'provider' => 'custom' // Our custom driver
],
...
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'custom', // Our custom driver
],
...
],
...
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => Modules\Pickandroll\Entities\User::class,
],
'custom' => [
'driver' => 'pickandrolluser', //Our Custom Auth Provider
'model' => Modules\Pickandroll\Entities\User::class,
]
],
and the custom module provider we register our custom auth provider
public function register()
{
Auth::provider('pickandrolluser', function ($app, array $config) {
return new PickandrollUserProvider($config['model']);
});
}
and the class PickandrollUserProvider that extends use Illuminate\Contracts\Auth\UserProvider;
I know it's complex but maybe it helps to understand this topic
How can i change the default user model to use other database table instead of users table in laravel 5.3, is adding
protected $table = 'my_table_name';
will do everything or do i have to change the providers and all.
I dont wish to use multiple authentication like admin, customers etc i just want one authentication model but not with the table "users".
I am preparing an application which has multiple type of users like admin, astrologers and users. all of them have different attributes so i cant use single model with access control in it so i have decided to divide the application into 3 websites to use single database and host them in subdomains like
admin.mywebsite.com
astrologer.mywebsite.com
www.mywebsite.com
earlier i was using multiauth/hesto plugin but for some strange reason it's not redirecting me to the intended url after login and registration. any help will be appreciated.
check this one Using Different Table for Auth in Laravel
Edit app/config/auth.php to change the table.
'table' => 'yourTable'
'model' => 'YourModel',
then your model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class YourModel extends Eloquent implements UserInterface, RemindableInterface
{
use UserTrait;
use RemindableTrait;
protected $table = 'your_table';
protected $fillable = array('UserName', 'Password');
public $timestamps = true;
public static $rules = array();
}
You can specify which database to use using the $connection attribute in your model:
class MyModel extends Eloquent
{
protected $connection = 'another-database-connection';
}
I'm not sure it's what you're looking for tho. That said, if you want to use the same Laravel application for multiple subdomains, I'd recommend checking the documentation which explains how to use subdomains in your routes:
https://laravel.com/docs/5.3/routing#route-group-sub-domain-routing
This would allow you to have a single User class and a single application but have specific routes for each of your 3 subdomains.
go to your config\auth.php
modify the configuration
'guards' => [
'astrologer' =>[
'driver' => 'session',
'provider' => 'astrologer',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
'providers' => [
'astrologer' => [
'driver' => 'eloquent',
'model' => App\Astrologer::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
],
See answer here for more details: Can anyone explain Laravel 5.2 Multi Auth with example
Go to config/auth.php
Change the provider for this case I changed the api provider from user to custom_user and then use custom_user model class
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver'=>'passport',
'provider'=>'custom_user'
],
]
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'custom_user' => [
'driver' => 'eloquent',
'model' => App\custom_user::class,
],
]
I am trying to authenticate users and admin form user table and admin table respectively. I am using the User model as provided by laravel out of the box and created the same for Admin. I have added a guard key and provider key into auth.php.
Guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
Routes
Route::group(['middleware' => ['web']], function () {
// Login Routes.
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes.
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
I have created a directory called AuthAdmin where Laravel's default AuthController.php and PasswordController.php files are present. (Namespace Modified accordingly)
First of all, in Laravel's docs mentioned that how to specify custom guard while authenticating like this which isn't working.
There's another method mentioned in Laravel's docs to use a guard which is not working too.
It would be beneficial if someone could resolve the issues and correct me if I am wrong.
After lots of digging and lots of questions & answers I have finally managed to work Laravel 5.2 Multi Auth with two table, So I'm writing Answer of my own Question.
How to implement Multi Auth in Laravel 5.2
As Mentioned above.
Two table admin and users
Laravel 5.2 has a new artisan command.
php artisan make:auth
it will generate basic login/register route, view and controller for user table.
Make a admin table as users table for simplicity.
Controller For Admin
app/Http/Controllers/AdminAuth/AuthController
app/Http/Controllers/AdminAuth/PasswordController
(note: I just copied these files from app/Http/Controllers/Auth/AuthController here)
config/auth.php
//Authenticating guards
'guards' => [
'user' =>[
'driver' => 'session',
'provider' => 'user',
],
'admin' => [
'driver' => 'session',
'provider' => 'admin',
],
],
//User Providers
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
'admin' => [
'driver' => 'eloquent',
'model' => App\Admin::class,
]
],
//Resetting Password
'passwords' => [
'clients' => [
'provider' => 'client',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
'admins' => [
'provider' => 'admin',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
route.php
Route::group(['middleware' => ['web']], function () {
//Login Routes...
Route::get('/admin/login','AdminAuth\AuthController#showLoginForm');
Route::post('/admin/login','AdminAuth\AuthController#login');
Route::get('/admin/logout','AdminAuth\AuthController#logout');
// Registration Routes...
Route::get('admin/register', 'AdminAuth\AuthController#showRegistrationForm');
Route::post('admin/register', 'AdminAuth\AuthController#register');
Route::get('/admin', 'AdminController#index');
});
AdminAuth/AuthController.php
Add two methods and specify $redirectTo and $guard
protected $redirectTo = '/admin';
protected $guard = 'admin';
public function showLoginForm()
{
if (view()->exists('auth.authenticate')) {
return view('auth.authenticate');
}
return view('admin.auth.login');
}
public function showRegistrationForm()
{
return view('admin.auth.register');
}
it will help you to open another login form for admin
creating a middleware for admin
class RedirectIfNotAdmin
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string|null $guard
* #return mixed
*/
public function handle($request, Closure $next, $guard = 'admin')
{
if (!Auth::guard($guard)->check()) {
return redirect('/');
}
return $next($request);
}
}
register middleware in kernel.php
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\RedirectIfNotAdmin::class,
];
use this middleware in AdminController
e.g.,
middleware('admin');
}
public function index(){
return view('admin.dashboard');
}
}
That's all needed to make it working and also to get json of authenticated admin use
`Auth::guard('admin')->user()`
**Edit - 1**
We can access authenticated user directly using
`Auth::user()`
but if you have two authentication table then you have to use
Auth::guard('guard_name')->user()
for logout
Auth::guard('guard_name')->user()->logout()
for authenticated user json
Auth::guard('guard_name')->user()
##Edit 2
Now you can download Laravel 5.2 Multiauth implemented Project http://imrealashu.in/code/laravel/multi-auth-with-laravel-5-2-2/
In case this helps anyone, and this may just be due to my lack of understanding of middleware, here's what I had to do to get this working (in addition to the steps taken by #imrealashu)...
In route.php:
Route::get('/admin', [
'middleware' => 'admin',
'uses' => 'AdminController#index'
]);
This is in the web middleware group. Before this I tried putting it in a separate admin middleware group and even in an auth:admin group but this didn't work, it only worked for me when I specified the middleware as admin on the route itself. I have no idea why this is but I hope it saves others from pulling their hair out like I did.
It's very easy in laravel 5.6. Just go to config/auth.php and add this line in providers array:
'admins' => [
'driver' => 'database',
'table' => 'admin_table'
]
Note that we used database for driver not eloquent.
Now add this to guards array:
'admin_guard' => [
'driver' => 'session',
'provider' => 'admins'
]
Now we're done! Use this when working with admins table:
Auth::guard('admin_guard')->User();
Cheers.