php - How to make laravel 8 laravel/ui auth multiple different table?

Install laravel/ui
composer require laravel/ui php artisan ui bootstrap --auth
I want to add auth with different table
app\auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
Answer
Solution:
The first step
php artisan make:model Admin -m
until message
- Model created successfully.
Created Migration: 2020_01_23_022811_create_admins_table *
change the code in the section : database/migrations/2020_01_23_022811_create_admins_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateAdminsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('admins', function (Blueprint $table) {
$table->id();
$table->string('name', 150);
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('phone', 20)->nullable();
$table->enum('level_access', ['admin', 'superadmin'])->default('admin');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('admins');
}
}
*and run the command *
** php artisan migrate **
- then change the code *
** app/Models/Admin.php **
<?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;
use Illuminate\Support\Str;
class Admin extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'phone', 'level_access'
];
/**
* 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',
];
/**
* Send the password reset notification.
*
* @param string $token
* @return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token, 'admin.password.reset', 'admins'));
}
}
next
php artisan make:controller AuthAdmin/LoginController
php artisan make:controller Admin/DashboardController -r
- then change the code *
app/Http/Controllers/AuthAdmin/LoginController.php
<?php
namespace App\Http\Controllers\AuthAdmin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
{
public function __construct() {
$this->middleware('guest:admin', ['except' => ['logout']]);
}
/**
*
* @return type
*/
public function showLoginForm() {
return view('authadmin.login');
}
/**
*
* @param Request $request
* @return type
*/
public function login(Request $request) {
// Validate the form data
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6'
]);
// Attempt to log the user in
if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password], $request->remember)) {
// if successful, then redirect to their intended location
return redirect()->route('admin.dashboard');
}
// if unsuccessful, then redirect back to the login with the form data
return redirect()->back()->withInput($request->only('email', 'remember'))
->withErrors(['password' => [
'These credentials don\'t match our records.',
'Or Incorrect Password'
]]);
}
/**
*
* @return type
*/
public function logout() {
Auth::guard('admin')->logout();
return redirect()->route('admin.login');
}
}
app/Http/Controllers/Admin/DashboardController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.dashboard');
}
}
*Next create a new folder in *
** resources/views **
- resources/views/admin
- resources/views/authadmin
*Next create the dashboard.blade.php file in the admin folder folder
@extends('layouts.admin')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">{{ __('Hello, ') }} {{Auth::guard('admin')->user()->name}}</div>
<div class="card-body">
</div>
</div>
</div>
</div>
</div>
@endsection
*Next create the login.blade.php file in the authadmin folder folder
@extends('layouts.admin')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Login Admin') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('admin.login.submit') }}">
@csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control @error('email') is-invalid @enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
@error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control @error('password') is-invalid @enderror" name="password" required autocomplete="current-password">
@error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
@endsection
*Next create the admin.blade.php file in the resources/views/layouts/admin.blade.php folder folder
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="{{asset('dist/css/bootstrap.min.css')}}" >
</head>
<body>
<div id="app">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="{{ url('/') }}">
{{ config('app.name', 'Laravel') }}
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<!-- Left Side Of Navbar -->
<ul class="navbar-nav mr-auto">
</ul>
<!-- Right Side Of Navbar -->
<ul class="navbar-nav ml-auto">
<!-- Authentication Links -->
@if(Auth::guard('admin')->check())
{{-- <li class="nav-item">
<a class="nav-link" href="#">{{ __('List Of Question') }}</a>
</li> --}}
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
{{ Auth::user()->name }}
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{{ route('admin.logout') }}"
onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('admin.logout') }}" method="POST" class="d-none">
@csrf
</form>
</div>
</li>
@endif
</ul>
</div>
</div>
</nav>
<main class="py-4">
@yield('content')
</main>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="{{asset('dist/js/jquery-3.2.1.min.js')}}" ></script>
<script src="{{asset('dist/js/bootstrap.bundle.min.js')}}" ></script>
<script src="{{asset('dist/js/bootstrap.min.js')}}" ></script>
</body>
</html>
*next change the configuration in the file config/auth.php *
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'admin' => [
'driver' => 'session',
'provider' => 'admins',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
...
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
...
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
'admins' => [
'provider' => 'admins',
'table' => 'password_resets',
'expire' => 60,
'throttle' => 60,
],
],
*change Handler in file : app/Exceptions/Handler.php *
<?php
namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* @var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* @var array
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->reportable(function (Throwable $e) {
//
});
}
protected function unauthenticated($request, AuthenticationException $exception) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Unauthenticated.'], 401);
}
$guard = \Arr::get($exception->guards(), 0);
switch ($guard) {
case 'admin':
$login = 'admin.login';
break;
default:
$login = 'login';
break;
}
return redirect()->guest(route($login));
}
}
*add route for admin in file : routes/web.php *
Route::group(['prefix' => 'admin'], function() {
/**
* Login
*/
Route::get('login', [App\Http\Controllers\AuthAdmin\LoginController::class, 'showLoginForm'])->name('admin.login');
Route::post('login', [App\Http\Controllers\AuthAdmin\LoginController::class, 'login'])->name('admin.login.submit');
Route::middleware(['auth:admin'])->group(function () {
Route::get('/', [App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('admin.dashboard');
/*
* Logout
*/
Route::post('logout/', [App\Http\Controllers\AuthAdmin\LoginController::class, 'logout'])->name('admin.logout');
});
});
add seeder for Admin default data
php artisan make:seeder AdminSeeder
*edit AdminSeeder in file : database/seeders/AdminSeeder.php *
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Admin;
use Illuminate\Support\Facades\Hash;
class AdminSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$arrayAdmin = [
[
'name' => 'Valentino Rossi',
'email' => '[email protected]',
'level_access' => 'superadmin',
'password' => Hash::make('123456'),
],
[
'name' => 'Valentino Rossa',
'email' => '[email protected]',
'level_access' => 'admin',
'password' => Hash::make('123456'),
],
];
foreach($arrayAdmin as $value) {
Admin::create($value);
}
}
}
*AND edit DatabaseSeeder in file : database/seeders/DatabaseSeeder.php *
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// \App\Models\User::factory(10)->create();
$this->call([
UserSeeder::class,
AdminSeeder::class,
]);
}
}
and run the command php artisan migrate:refresh --seed
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: foreign key constraint is incorrectly formed laravel
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.