如何在Laravel中同时实现管理员和客户面板

时间:2019-05-14 10:24:48

标签: laravel

** NewBee

** Laravel

我想使用URL http://127.0.0.1:8000/admin访问管理面板,并使用URL http://127.0.0.1:8000/访问客户面板

Customer Login: http://127.0.0.1:8000/login

Admin Login: http://127.0.0.1:8000/admin/

我已经设置了一个会话变量,以识别用户是否在我的admin or customer中是AdminController.php,并检查该用户必须是管理员才能访问的每个功能。下面是脚本

AdminController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use Session;

class AdminController extends Controller
{
    public function index() {
        return view('admin.index');
    }

    public function login(Request $request) {

        Auth::attempt(['email' => $request->email, 'password' => $request->password, 'user_type' => 'admin']);

        //was any of those correct ?
        if ( Auth::check() ) {
            //send them where they are going 
            Session::put('userType', 'admin');
            return redirect()->route('admin.dashboard');
        }

        return redirect('/admin')->with('flash_message', 'Invalid Credentials');
    }

    public function dashboard() {
        if( Session::has('userType') and Session::get('userType') == 'admin' )
            return view('admin.dashboard');
        else
            return redirect('/admin')->with('flash_message', 'Please login to access');
    }

    public function posts() {
        if( Session::has('userType') and Session::get('userType') == 'admin' )
            return view('admin.posts');
        else
            return redirect('/admin')->with('flash_message', 'Please login to access');
    }

    public function logout() {
        Session::flush();
        return redirect()->route('admin');
    }
}

我正在检查用户在if( Session::has('userType') and Session::get('userType') == 'admin' )这样的所有功能中是否是管理员。那么有什么办法可以做得更好呢?????

现在,当我登录到管理面板时,我也可以为客户访问http://127.0.0.1:8000/home,但是由于我已经以管理员身份而不是以客户身份登录,因此不应访问该帐户。

现在如何为两种不同类型的用户启用会话变量并确保用户的可访问性?

web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

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

Route::get('/home', 'HomeController@index')->name('home');

Auth::routes();

Route::get('/admin', 'AdminController@index')->name('admin');
Route::post('/admin/login', 'AdminController@login')->name('admin.login');
Route::get('/admin/dashboard', 'AdminController@dashboard')->name('admin.dashboard');
Route::get('/admin/posts', 'AdminController@posts')->name('admin.posts');
Route::get('/admin/logout', 'AdminController@logout')->name('admin.logout');

1 个答案:

答案 0 :(得分:0)

您需要的是middleware或某种第三方软件包,例如laratrsut