doujuanju3076 2019-05-11 14:56 采纳率: 0%
浏览 104

无法使用guard在laravel中运行登录应用程序

I am creating login application with the help of middleware. The issue is now when i run the application i get the error message :

Type error: Argument 2 passed to Illuminate\Auth\SessionGuard::__construct() must implement interface Illuminate\Contracts\Auth\UserProvider, null given, called in C:\wamp64\www\Login\vendor\laravel\framework\src\Illuminate\Auth\AuthManager.php on line 123

Actually i want to implement roles based check for which i have used guard One is simple user and other in admin. Please help to sort out my issue.

Here is my complete code:

LoginController.php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;

class LoginController extends Controller {
    //
    public function getLogin() {
        return view('login');
    }
    public function postLogin(Request $request) {
        // Validate the form data
        $this->validate($request, [
            'email' => 'required|email',
            'password' => 'required',
        ]);
        // Attempt to log the user in
        // Passwordnya pake bcrypt
        if (Auth::guard('admin')->attempt(['email' => $request->email, 'password' => $request->password])) {
            // if successful, then redirect to their intended location
            return redirect()->intended('/admin');
        } else if (Auth::guard('user')->attempt(['email' => $request->email, 'password' => $request->password])) {
            return redirect()->intended('/user');
        }
    }
    public function logout() {
        if (Auth::guard('admin')->check()) {
            Auth::guard('admin')->logout();
        } elseif (Auth::guard('user')->check()) {
            Auth::guard('user')->logout();
        }
        return redirect('/');
    }
}

Controller.php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

Model: Admin.php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class Admin extends Authenticatable {
    use Notifiable;
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

User.php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Config/auth.php

return [

    /*
            |--------------------------------------------------------------------------
            | Authentication Defaults
            |--------------------------------------------------------------------------
            |
            | This option controls the default authentication "guard" and password
            | reset options for your application. You may change these defaults
            | as required, but they're a perfect start for most applications.
            |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
            |--------------------------------------------------------------------------
            | Authentication Guards
            |--------------------------------------------------------------------------
            |
            | Next, you may define every authentication guard for your application.
            | Of course, a great default configuration has been defined for you
            | here which uses session storage and the Eloquent user provider.
            |
            | All authentication drivers have a user provider. This defines how the
            | users are actually retrieved out of your database or other storage
            | mechanisms used by this application to persist your user's data.
            |
            | Supported: "session", "token"
            |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
        'admin' => [
            'driver' => 'session',
            'provider' => 'admin',
        ],
        'admin-api' => [
            'driver' => 'token',
            'provider' => 'admin',
        ],
        'user' => [
            'driver' => 'session',
            'provider' => 'user',
        ],
        'user-api' => [
            'driver' => 'token',
            'provider' => 'user',
        ],
    ],

    /*
            |--------------------------------------------------------------------------
            | User Providers
            |--------------------------------------------------------------------------
            |
            | All authentication drivers have a user provider. This defines how the
            | users are actually retrieved out of your database or other storage
            | mechanisms used by this application to persist your user's data.
            |
            | If you have multiple user tables or models you may configure multiple
            | sources which represent each model / table. These sources may then
            | be assigned to any extra authentication guards you have defined.
            |
            | Supported: "database", "eloquent"
            |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
        'admin' => [
            'driver' => 'eloquent',
            'model' => App\Admin::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
            |--------------------------------------------------------------------------
            | Resetting Passwords
            |--------------------------------------------------------------------------
            |
            | You may specify multiple password reset configurations if you have more
            | than one user table or model in the application and you want to have
            | separate password reset settings based on the specific user types.
            |
            | The expire time is the number of minutes that the reset token should be
            | considered valid. This security feature keeps tokens short-lived so
            | they have less time to be guessed. You may change this as needed.
            |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

routes.php

Route::get('/', function () {
    return view('welcome');
});

// hanya untuk tamu yg belum auth
Route::get('/login', 'LoginController@getLogin')->middleware('guest');
Route::post('/login', 'LoginController@postLogin');
Route::get('/logout', 'LoginController@logout');;

Route::get('/admin', function() {
  return view('admin');
})->middleware('auth:admin');

Route::get('/user', function() {
  return view('user');
})->middleware('auth:user');

admin.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <h2>Admin Page {{ Auth::guard('admin')->user()->name }}</h2>
  <br>
  <a href="/logout">Logout {{ Auth::guard('admin')->user()->name }} ??</a>
</body>
</html>

user.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <h2>User Page.. halo {{Auth::guard('user')->user()->name}}</h2>
  <br>
  <a href="/logout">Logout {{ Auth::guard('user')->user()->name }} ??</a>
</body>
</html>

login.blade.php

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <fieldset style="width:300px; margin:100px auto">
    <legend>Form Login</legend>
    <form action="/login" method="post">
      {{ csrf_field() }}
      <table>
        <tr>
          <td>Email</td>
          <td>:</td>
          <td><input type="text" name="email" id="email"></td>
        </tr>
        <tr>
          <td>Password</td>
          <td>:</td>
          <td><input type="password" name="password" id="password"></td>
        </tr>
      </table>
      <button type="submit">Login</button>
    </form>
  </fieldset>
</body>

</html>

redirectIfAuthenticated.php

namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
  /**
   * 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 = null)
  {
    if (Auth::guard('admin')->check()) {
      return redirect('/admin');
    } else if (Auth::guard('user')->check()) {
      return redirect('/user');

    }
    return $next($request);
  }
}

Authenticate.php

    namespace App\Http\Middleware;
    use Illuminate\Auth\Middleware\Authenticate as Middleware;
    use Illuminate\Support\Facades\Auth;
    class Authenticate extends Middleware
    {
      /**
       * Get the path the user should be redirected to when they are not authenticated.
       *
       * @param  \Illuminate\Http\Request  $request
       * @return string
       */
      protected function redirectTo($request)
      {
        if (Auth::guard('admin')->check()) {
          return redirect('/admin');
        } else if (Auth::guard('user')->check()) {
          return redirect('/user');

        }
      }
    }

App/Exceptions/Handler.php

namespace App\Exceptions;
use Illuminate\Auth\AuthenticationException;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
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 = [
        'password',
        'password_confirmation',
    ];
    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        parent::report($exception);
    }
    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
    protected function unauthenticated($request, \Illuminate\Auth\AuthenticationException $exception)
    {
      if($request->expectsJson()){
        return response()->json(['error' => 'Unauthenticated.'], 401);
      }
      return redirect('/login');
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?