Login System with Gate and Redirect

  • login 1

    Admin dashboard
  • login 2

    Edit user roles
  • login 3

    User dashboard

Source code: https://github.com/sunnygreentea/login


Features:

Route:

Namespace, prefix, name, group, resource except

Route::namespace('Admin')->prefix('admin')->name('admin.')->group(function () {
	Route::get('/home', 'HomeController@index')->name('home');
	Route::resource ('/users', 'UserController', ['except' => ['show', 'create', 'store']]);
	Route::resource('/posts', 'PostController');
	Route::resource('/comments', 'CommentController');
	Route::get('/posts-active','PostController@activePosts') ->name('activeposts');
	Route::get('/posts-draft','PostController@draftPosts') ->name('draftposts');
});

Gate:

Defined in app/Providers/AuthServiceProvider.php

Gate::define('is_admin', function ($user){
            return $user->hasRole('admin');
        });

Applied in User controller:

if(Gate::allows('is_admin')) {......}

Redirect:

app/Http/Controllers/Auth/LoginController.php: change default redirectTo: if it is admin, redirect to admin.users.index, otherwise redirect to default route “home”.

public function redirectTo() {
        if(Auth::user()->hasRole('admin')) {
            $this->redirectTo = route('admin.users.index');