Laravel 5.5 administrator route issue - laravel

I have the below mentioned route:
Route::get('/', 'HomeController#index');
Route::get('administrator', array('before' => 'auth', 'uses' => 'Administrator\IndexController#index'));
//Route::get('/administrator', 'Administrator\IndexController#index');
Route::group(['prefix' => 'administrator'], function() {
Route::get('login', 'Administrator\IndexController#index')->name('login');
Route::post('login', 'Auth\LoginController#doLogin');
Route::get('logout', 'Auth\LoginController#logout');
});
My intention is when someone try to access http://127.0.0.1:8000/administrator/ this will go directly to the login page of the administrator.
However, when I tried to access the same, it said 404 not found.
IndexController under Administrator folder is looks below:
class IndexController extends Controller {
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('guest')->except('doLogout');
}
public function index() {
//$session = session()->all();
if(Auth::check() == 1){
return Redirect::intended('/administrator/dashboard')->with('successMessage', 'You have successfully logged in.');
}
//print_r($session);
//echo $session['_token'];
//if($session['_token'] == '')
$data = array();
$data['title'] = "Shop To My Door - Administrator Panel";
return view('Administrator.index.index', $data);
}
}

You have route and group with the same name "administrator"
My suggestion for routing:
Route::get('/', 'HomeController#index');
Route::group(['prefix' => 'administrator'], function() {
Route::get('/', 'Administrator\IndexController#index');
Route::get('login', 'Administrator\IndexController#login');
Route::post('login', 'Auth\LoginController#doLogin');
Route::get('logout', 'Auth\LoginController#logout');
});

Related

Having problem with authentication via middleware and also page not found in laravel

**I just want to know what did i do wrong. Below are the code. Whenever I try to excess
127.0.0.1::8000/admin/profile
without login, it shows me error rather than redirecting me to login page as I have used middleware so it should not show me error but redirect me to admin login page which is not happening here. Also after when i logged in and try to excess
127.0.0.1::8000/admin/profile/edit/{id} it show 404 page not found. why?*
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
Route::prefix('admin')->name('admin.')->group(function(){
Route::middleware('admin')->group(function(){
Route::get('/dashboard', [AdminController::class, 'displayDashboard'])->name('dashboard');
Route::get('/logout', [AdminController::class, 'logout'])->name('logout');
Route::get('profile', [AdminProfileController::class, 'displayProfile'])->name('admin.profile');
Route::get('profile/edit/{id}', [AdminProfileController::class, 'editProfile'])->name('profile.edit');
});
Route::get('/login', [AdminController::class, 'login'])->name('login')->middleware('guest:admin');
Route::post('/login', [AdminController::class, 'loginvalidate'])->name('loginvalidate')->middleware('guest:admin');
});
AdminProfileController.blade.php
class AdminProfileController extends Controller
{
public function displayProfile()
{
$loggedinUser = Auth::guard('admin')->user();
return view('admin.profile.profile_master', compact('loggedinUser'));
}
public function editProfile($id)
{
return view('admin.profile.profile_edit');
}
}
Admin middleware
public function handle(Request $request, Closure $next)
{
if(!Auth::guard('admin')->check())
{
return redirect()->route('admin.login');
}
return $next($request);
}

Controller action is not available

I am not familiar with laravel but from what I red I made this:
My controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ChatController extends Controller
{
public function index(Request $request)
{
var_dump(123123);die;
if (!Auth::check()) {
return redirect('/');
}
return 1;
}
}
Now I am trying to request it like domain.com/open-chat. And my web.php configuration about it is:
Route::get('/open-chat', 'ChatController#index');
But I am getting redirected to the home page. I`ve checked the middleware controllers if some of it redirects me but no. The other controllers ( which were already made when I came ) works fine. What am I missing ?
EDIT
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('/clear-cache', function() {
Artisan::call('cache:clear');
return "Cache is cleared";
});
Route::get('/config-cache', function() {
Artisan::call('config:cache');
return "Config is cleared";
});
Route::get('/view', function() {
Artisan::call('view:clear');
return "View is cleared";
});
/* Route::get('/', function () {
return view('welcome');
}); */
Route::group(['prefix' => 'siteadmin', 'namespace' => 'Admin'], function () {
Route::get('/', 'Auth\LoginController#showLoginForm');
Route::post('login', 'Auth\LoginController#login')->name('admin.login');
Route::post('logout', 'Auth\LoginController#logout')->name('admin.logout');
});
Route::group(['prefix'=>'siteadmin', 'namespace' => 'Admin','middleware' => 'auth'], function () {
Route::get('/dashboard', 'DashboardController#index')->name('dashboard.index');
Route::get('/edit-profile', 'CommonController#editProfile');
Route::post('/updateprofile', 'CommonController#updateprofile');
/**
Routes for site settings
**/
Route::get('/site-settings', 'SiteSettingController#index')->name('sitesettings.index');
Route::post('/site-settings/store', 'SiteSettingController#store')->name('sitesettings.save');
Route::get('/subject-categories', 'SubjectCategoriesController#index')->name('subject-categories.index');
Route::get('/subject-categories/create', 'SubjectCategoriesController#create')->name('subject-categories.create');
Route::post('/subject-categories/store', 'SubjectCategoriesController#store')->name('subject-categories.store');
Route::get('/subject-categories/edit/{id}', 'SubjectCategoriesController#edit')->name('subject-categories.edit');
Route::post('/subject-categories/update/{id}', 'SubjectCategoriesController#update')->name('subject-categories.update');
Route::get('/subject-categories/drop/{id}', 'SubjectCategoriesController#drop')->name('subject-categories.drop');
Route::post('/subject-categories/delete-image/{id}', 'SubjectCategoriesController#deleteImage');
/**
Routes for teachers users
**/
Route::get('/users/teachers', ['middleware'=>'auth','uses'=>'UserController#getTeachersList'])->name('teachers.index');
Route::get('/users/teachers/create', ['middleware'=>'auth','uses'=>'UserController#createTeacher'])->name('teachers.create');
Route::post('/users/teachers/save', ['middleware'=>'auth','uses'=>'UserController#saveTeacher'])->name('teachers.save');
Route::get('/users/teachers/edit/{id}', ['middleware'=>'auth','uses'=>'UserController#editTeacher'])->name('teachers.edit');
Route::get('/users/teachers/show/{id}', ['middleware'=>'auth','uses'=>'UserController#showTeacher'])->name('teachers.show');
Route::post('/users/teachers/update/{id}', ['middleware'=>'auth','uses'=>'UserController#updateTeacher'])->name('teachers.update');
Route::get('/users/teachers/delete/{id}', ['middleware'=>'auth','uses'=>'UserController#deleteTeacher']);
Route::get('/users/teachers/change-status/{id}', ['middleware'=>'auth','uses'=>'UserController#changeTeacherStatus']);
Route::post('/users/get-cities-by-country', ['middleware'=>'auth','uses'=>'UserController#getCitiesByCountry']);
Route::get('/users/teachers/messages/{id}', ['middleware'=>'auth','uses'=>'UserController#getTeacherMessageThreads'])->name('teachers.messages');
Route::get('/users/teachers/view-message/{id}', ['middleware'=>'auth','uses'=>'UserController#getAllMessagesByThreadID'])->name('teacher.view-message');
Route::post('/users/teachers/delete-profile-image/{id}', ['middleware'=>'auth','uses'=>'UserController#deleteTeacherProfileImage']);
/**
Routes for driver users
**/
Route::get('/users/students', ['middleware'=>'auth','uses'=>'UserController#getStudentsList'])->name('students.index');
Route::get('/users/students/create', ['middleware'=>'auth','uses'=>'UserController#createStudent'])->name('students.create');
Route::post('/users/students/save', ['middleware'=>'auth','uses'=>'UserController#saveStudent'])->name('students.save');
Route::get('/users/students/edit/{id}', ['middleware'=>'auth','uses'=>'UserController#editStudent'])->name('students.edit');
Route::get('/users/students/show/{id}', ['middleware'=>'auth','uses'=>'UserController#showStudent'])->name('students.show');
Route::post('/users/students/update/{id}', ['middleware'=>'auth','uses'=>'UserController#updateStudent'])->name('students.update');
Route::get('/users/students/delete/{id}', ['middleware'=>'auth','uses'=>'UserController#deleteStudent']);
Route::get('/users/students/change-status/{id}', ['middleware'=>'auth','uses'=>'UserController#changeStudentStatus']);
/**
Routes for countries
**/
Route::get('/countries', ['middleware'=>'auth','uses'=>'CountryController#index'])->name('countries.index');
Route::get('/countries/create', ['middleware'=>'auth','uses'=>'CountryController#create'])->name('countries.create');
Route::post('/countries/save', ['middleware'=>'auth','uses'=>'CountryController#store'])->name('countries.save');
Route::get('/countries/edit/{id}', ['middleware'=>'auth','uses'=>'CountryController#edit'])->name('countries.edit');
Route::get('/countries/show/{id}', ['middleware'=>'auth','uses'=>'CountryController#show'])->name('countries.show');
Route::post('/countries/update/{id}', ['middleware'=>'auth','uses'=>'CountryController#update'])->name('countries.update');
Route::get('/countries/delete/{id}', ['middleware'=>'auth','uses'=>'CountryController#destroy']);
Route::get('/countries/change-status/{id}', ['middleware'=>'auth','uses'=>'CountryController#changeStatus']);
Route::post('/countries/delete-image/{id}', ['middleware'=>'auth','uses'=>'CountryController#deleteImage']);
/**
Routes for cities
**/
Route::get('/cities', ['middleware'=>'auth','uses'=>'CityController#index'])->name('cities.index');
Route::get('/cities/create', ['middleware'=>'auth','uses'=>'CityController#create'])->name('cities.create');
Route::post('/cities/save', ['middleware'=>'auth','uses'=>'CityController#store'])->name('cities.save');
Route::get('/cities/edit/{id}', ['middleware'=>'auth','uses'=>'CityController#edit'])->name('cities.edit');
Route::get('/cities/show/{id}', ['middleware'=>'auth','uses'=>'CityController#show'])->name('cities.show');
Route::post('/cities/update/{id}', ['middleware'=>'auth','uses'=>'CityController#update'])->name('cities.update');
Route::get('/cities/delete/{id}', ['middleware'=>'auth','uses'=>'CityController#destroy']);
Route::get('/cities/change-status/{id}', ['middleware'=>'auth','uses'=>'CityController#changeStatus']);
Route::post('/cities/delete-image/{id}', ['middleware'=>'auth','uses'=>'CityController#deleteImage']);
/**
Routes for subjects
**/
Route::get('/subjects', ['middleware'=>'auth','uses'=>'SubjectController#index'])->name('subjects.index');
Route::get('/subjects/create', ['middleware'=>'auth','uses'=>'SubjectController#create'])->name('subjects.create');
Route::post('/subjects/save', ['middleware'=>'auth','uses'=>'SubjectController#store'])->name('subjects.save');
Route::get('/subjects/edit/{id}', ['middleware'=>'auth','uses'=>'SubjectController#edit'])->name('subjects.edit');
Route::get('/subjects/show/{id}', ['middleware'=>'auth','uses'=>'SubjectController#show'])->name('subjects.show');
Route::post('/subjects/update/{id}', ['middleware'=>'auth','uses'=>'SubjectController#update'])->name('subjects.update');
Route::get('/subjects/delete/{id}', ['middleware'=>'auth','uses'=>'SubjectController#destroy']);
Route::get('/subjects/change-status/{id}', ['middleware'=>'auth','uses'=>'SubjectController#changeStatus']);
/**
Routes for classes
**/
Route::get('/classes', ['middleware'=>'auth','uses'=>'ClassController#index'])->name('classes.index');
Route::get('/classes/create', ['middleware'=>'auth','uses'=>'ClassController#create'])->name('classes.create');
Route::post('/classes/save', ['middleware'=>'auth','uses'=>'ClassController#store'])->name('classes.save');
Route::get('/classes/edit/{id}', ['middleware'=>'auth','uses'=>'ClassController#edit'])->name('classes.edit');
Route::get('/classes/show/{id}', ['middleware'=>'auth','uses'=>'ClassController#show'])->name('classes.show');
Route::post('/classes/update/{id}', ['middleware'=>'auth','uses'=>'ClassController#update'])->name('classes.update');
Route::get('/classes/delete/{id}', ['middleware'=>'auth','uses'=>'ClassController#destroy']);
Route::get('/classes/change-status/{id}', ['middleware'=>'auth','uses'=>'ClassController#changeStatus']);
Route::post('/classes/get-subjects-by-category', ['middleware'=>'auth','uses'=>'ClassController#getSubjectsByCategory']);
/**
Routes for sliders
**/
Route::get('/sliders', 'SliderController#index')->name('sliders.index');
Route::get('/sliders/create', 'SliderController#create')->name('sliders.create');
Route::post('/sliders/store', 'SliderController#store')->name('sliders.save');
Route::get('/sliders/edit/{id}', 'SliderController#edit')->name('sliders.edit');
Route::post('/sliders/update/{id}', 'SliderController#update')->name('sliders.update');
Route::get('/sliders/delete/{id}', 'SliderController#destroy')->name('sliders.delete');
Route::get('/sliders/change-status/{id}', ['middleware'=>'auth','uses'=>'SliderController#changeStatus']);
Route::post('/sliders/delete-image/{id}', 'SliderController#deleteImage');
/**
Routes for teacher classes
**/
Route::get('/teacher-classes', 'TeacherClassController#index')->name('teacher-classes.index');
Route::get('/teacher-classes/create', 'TeacherClassController#create')->name('teacher-classes.create');
Route::post('/teacher-classes/store', 'TeacherClassController#store')->name('teacher-classes.save');
Route::get('/teacher-classes/edit/{id}', 'TeacherClassController#edit')->name('teacher-classes.edit');
Route::post('/teacher-classes/update/{id}', 'TeacherClassController#update')->name('teacher-classes.update');
Route::get('/teacher-classes/delete/{id}', 'TeacherClassController#destroy')->name('teacher-classes.delete');
Route::post('/teacher-classes/get-subjects-by-category', 'TeacherClassController#getSubjectsByCategory');
Route::post('/teacher-classes/get-classes-by-category-and-subject', 'TeacherClassController#getClassesBySubjectAndCategory');
/**
Routes for orders
**/
Route::get('/orders', 'OrderController#index')->name('orders.index');
Route::get('/orders/show/{id}', 'OrderController#show')->name('orders.show');
Route::get('/orders/export-orders', 'OrderController#exportOrders')->name('orders.export-orders');
/**
Routes for bookings
**/
Route::get('/bookings', 'BookingController#index')->name('bookings.index');
Route::get('/bookings/teacher-bookings/{teacher_id}', 'BookingController#getTeacherAllBookings')->name('bookings.bookings');
Route::get('/bookings/show/{id}', 'BookingController#show')->name('bookings.show');
Route::get('/bookings/export-teacher-bookings/{teacher_id}', 'BookingController#exportTeacherBookings')->name('bookings.export-teacher-bookings');
/**
Routes for bookings
**/
Route::get('/messages', 'MessageController#index')->name('messages.index');
Route::get('/messages/show/{id}', 'MessageController#show')->name('messages.show');
/**
Routes for reviews
**/
Route::get('/reviews', 'ReviewController#index')->name('reviews.index');
Route::get('/reviews/show/{id}', 'ReviewController#show')->name('reviews.show');
/**
Routes for blogs
**/
Route::get('/blogs', 'BlogController#index')->name('blogs.index');
Route::get('/blogs/create', 'BlogController#create')->name('blogs.create');
Route::post('/blogs/store', 'BlogController#store')->name('blogs.save');
Route::get('/blogs/edit/{id}', 'BlogController#edit')->name('blogs.edit');
Route::post('/blogs/update/{id}', 'BlogController#update')->name('blogs.update');
Route::get('/blogs/delete/{id}', 'BlogController#destroy')->name('blogs.delete');
Route::get('/blogs/change-status/{id}', ['middleware'=>'auth','uses'=>'BlogController#changeStatus']);
Route::post('/blogs/delete-image/{id}', 'BlogController#deleteImage');
});
Auth::routes();
Route::get('{locale?}', 'HomeController#index');
Route::get('/en', 'HomeController#index');
Route::get('/open-chat', 'ChatController#index');
Route::get('/ar', 'HomeController#index');
Route::get('/home', 'HomeController#index')->name('home');
Route::post('/get-cities-by-country', 'SearchController#getCitiesByCountry');
Route::post('/get-subjects-by-category', 'SearchController#getSubjectsByCategory');
Route::post('/register', 'CommonController#register');
Route::post('/login', 'CommonController#login');
Route::post('/forgot-password', 'CommonController#forgotPassword');
Route::get('/{locale?}/reset-password/{token}', 'CommonController#resetPassword');
Route::post('/{locale?}/resetpassword', 'CommonController#resetNewPassword')->name('reset-pass');
Route::get('/{locale?}/classes/search', 'ClassController#searchClasses')->name('search');
Route::get('/{locale?}/classes/all-cities', 'ClassController#getAllCitiesClasses');
Route::get('/{locale?}/classes/{type}/{id}', 'ClassController#getClassesByType');
Route::get('/{locale?}/view-class/{id}', 'ClassController#viewTeacherClassDetails')->name('view-class');
Route::get('/{locale?}/finish-class/{id}', 'ClassController#finishTeacherClass')->name('finish-class');
Route::post('/create-booking', 'CommonController#createBooking');
Route::post('/{locale?}/submit-review', 'CommonController#submitReview');
Route::get('/{locale?}/blogs', 'HomeController#getAllBlogs')->name('blogs');
Route::get('/{locale?}/blogs/{slug}', 'HomeController#getBlogDetails')->name('blogs.detail');
Route::get('/paypal/checkout/{order}/completed', [
'name' => 'PayPal Express Checkout',
'as' => 'paypal.checkout.completed',
'uses' => 'User\BookingController#completed',
]);
Route::get('/paypal/checkout/{order}/cancelled', [
'name' => 'PayPal Express Checkout',
'as' => 'paypal.checkout.cancelled',
'uses' => 'User\BookingController#cancelled',
]);
Route::post('/webhook/paypal/{order?}/{env?}', [
'name' => 'PayPal Express IPN',
'as' => 'webhook.paypal.ipn',
'uses' => 'User\BookingController#webhook',
]);
/**
User dashboard routes start
**/
Route::group(['prefix'=>'{locale?}/user', 'namespace' => 'User','middleware' => 'auth'], function () {
Route::get('/dashboard', 'DashboardController#index')->name('user.dashboard');
Route::get('/edit-profile', ['uses'=>'ProfileController#editProfile'])->name('user.edit-profile');
Route::post('/update-profile/{id}', ['uses'=>'ProfileController#updateProfile'])->name('user.update-profile');
Route::post('/update-image/{id}', ['uses'=>'ProfileController#updateUserImage'])->name('user.update-image');
Route::get('/change-password', ['uses'=>'ProfileController#changePassword'])->name('user.change-password');
Route::post('/update-password', ['uses'=>'ProfileController#updatePassword'])->name('user.update-password');
Route::get('/my-classes', ['uses'=>'ClassController#getTeacherClasses'])->name('user.my-classes');
Route::get('/my-classes/add-new-class', ['uses'=>'ClassController#createNewClass'])->name('user.add-new-class');
Route::post('/my-classes/save-class', ['uses'=>'ClassController#saveClass'])->name('user.save-class');
Route::get('/my-classes/edit-class/{id}', ['uses'=>'ClassController#editClass'])->name('user.edit-class');
Route::post('/my-classes/update-class/{id}', ['uses'=>'ClassController#updateClass'])->name('user.update-class');
Route::get('/my-classes/delete-class/{id}', ['uses'=>'ClassController#deleteClass']);
Route::post('/get-subjects-by-category', ['uses'=>'ClassController#getSubjectsByCategory']);
Route::post('/get-classes-by-category-and-subject', ['uses'=>'ClassController#getClassesByCategoryAndSubject']);
Route::get('/my-bookings', ['uses'=>'BookingController#getAllBookings'])->name('user.my-bookings');
Route::get('/my-bookings/view-booking-details/{id}', ['uses'=>'BookingController#viewBookingDetails'])->name('user.view-booking-details');
Route::get('/my-bookings/cancel-booking/{type}/{id}', ['uses'=>'BookingController#cancelBooking']);
Route::get('/my-bookings/accept-booking/{id}', ['uses'=>'BookingController#acceptBooking']);
Route::post('/make-a-payment', ['uses'=>'BookingController#makePayment'])->name('user.make-payment');
Route::get('/my-orders', ['uses'=>'OrderController#getAllOrders'])->name('user.my-orders');
Route::get('/messages', ['uses'=>'MessageController#getMessageThreads'])->name('user.messages');
Route::get('/messages/view-messages/{thread_id}', ['uses'=>'MessageController#getAllMessagesByThreadID'])->name('user.view-messages');
Route::post('/messages/send-message', ['uses'=>'MessageController#sendMessage']);
Route::get('/reviews', ['uses'=>'BookingController#getAllReviews'])->name('user.reviews');
});
Extended Controller.php:
<?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;
}
This rule Route::get('{locale?}', 'HomeController#index'); is catching all routes because it's always true. so Laravel follows this route.
the problem is not about Route::get('/open-chat', 'ChatController#index'); if you put any route after that one, it won't work.
we usually use this to catch all request to forward somewhere like Vuejs router or show 404 message.
Route::any('{catchall}', 'CatchAllController#handle')->where('catchall', '.*');
and these are pretty same. if you put Route::get('{locale?}', 'HomeController#index'); at the end of your router file, everything should work fine.
It's normal, var_dump doest stop the script and die should be die(). Instead, use dd(123123). Everything is fine with the controller.
Since the route doesn't have the auth middleware, we can assume that the route is open to everyone. In the controller, you are checking if the use is authenticated, if not, redirect to /.

Laravel Route Always Goes to index

In my Laravel application, I store a new user via Ajax to the DB. The app always calls the index method. What's wrong?
When I remove the Route::post('/users', 'Admin\UserController#store'); route there is a 405 error. That's correct. But why doesn't it go to the store method?
Controller
<?php
class UserController extends Controller
{
public function index()
{
return view('admin.user.index');
}
public function create()
{
//
}
public function store(UserCreateRequest $request)
{
$user = User::createFromRequest($request);
return response()->json(["id" => $user->id]);
}
}
Routes
Route::group(['prefix' => 'admin', 'as' => 'admin.', ], function () {
Route::get('/users/{user}', 'Admin\UserController#show')->name('users.show');
Route::post('/users', 'Admin\UserController#store');
Route::put('/users/{id}', 'Admin\UserController#updateFromDatatable');
Route::delete('/users/{id}', 'Admin\UserController#destroy');
Route::get('/users', 'Admin\UserController#index')->name('users.index');

working with laravel nested route group

I am using middleware for route groups and have three middlewares admin, teacher, and teacheradmin
Well admin is working fine but suppose I have 10 routes and all of them defined under group teacheradmin (working case for now)
but I want only 5 of those 10 routes to be accessed by middleware teacher and all 10 to be accessed by middleware teacheradmin
this is how I nested route groups
Route::group(['middleware' => 'teacheradmin'], function() {
//defined 5 routes only accessible by teacheradmin
Route::group(['middleware' => 'teacher'], function() {
//defined the other routes accessible by both teacher and teacheradmin
});
});
but the above nesting is not working, teacheradmin is not able to access the routes defined under teacher
plz I need a direction on how can I make it work
Update:
as per the answer I have defined middleware array for common routes
Route::group(['middleware' => ['teacher', 'teacheradmin']], function() {
//defined common routes
});
and the handle methods for teh two middleware is:
teacher
public function handle($request, Closure $next)
{
if(Auth::check())
{
if(Auth::user()->user_type != 'TEACHER')
{
return redirect()->route('dashboard');
}
return $next($request);
}
else
{
return redirect('/')
->withErrors('That username/password does not match, please try again !!!.');
}
}
teacheradmin
public function handle($request, Closure $next)
{
if(Auth::check())
{
if(Auth::user()->user_type != 'TEACHER_ADMIN')
{
return redirect()->route('dashboard');
}
return $next($request);
}
else
{
return redirect('/')
->withErrors('That username/password does not match, please try again !!!.');
}
}
and the dashboard route goes to this method
public function Dashboard(Request $request)
{
$user = Auth::user();
if($user->user_type === 'ADMIN') {
return redirect()->route('dashboardadmin');
} else if($user->user_type === 'TEACHER_ADMIN') {
return redirect()->route('dashboardteacher');
} else if($user->user_type === 'TEACHER') {
return redirect()->route('world_selection');
} else {
return redirect()->route('dashboardchild');
}
}
now the problem I am facing is when I am on dashboard and I try to access a common route as teacheradmin then it also goes to handle of teacher hence coming back to the same page again
Not sure why you are nesting them. You can attach multiple middleware via array notation to a group like this:
Route::group(['middleware' => 'teacheradmin'], function() {
//defined 5 routes only accessible by teacheradmin
});
Route::group(['middleware' => ['teacher', 'teacheradmin']], function() {
//defined the other routes accessible by both teacher and teacheradmin
});
Update:
I think what you are trying to do can be done by using just one middleware with middleware parameters:
Route::group(['middleware' => 'role:teacheradmin'], function() {
//defined 5 routes only accessible by teacheradmin
});
Route::group(['middleware' => 'role:teacher,teacheradmin'], function() {
//defined the other routes accessible by both teacher and teacheradmin
});
And in the role middleware:
public function handle($request, Closure $next, ...$roles)
{
dd($roles);
//Do your role checking here
return $next($request);
}
Disclaimer: ...$roles works from php 5.6 upwards.
As of Laravel 8 I would write it like:
Route::group(
['prefix' => 'v1', 'namespace' => 'Api'],
function(Router $router){
Route::get('/', function(){
return "Did you forget where you placed your keys??";
});
Route::post('/login', [LoginController::class, 'login']); //public
Route::get('/register', [LoginController::class, 'register']); //public
Route::group( //protected routes group
['middleware' => ['auth:sanctum']], //protected via some middleware
function () {
Route::get('/users', [UsersController::class, 'users']);
}
);
}
);

Laravel login and admin panel (after successful authentication) pages both on "/"

I want to have the login of my application and the admin panel (accessed after successful login) both accessible on "/".
I use the create method of a SessionsController for the login part (SessionsController.php):
class SessionsController extends \BaseController {
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
if ( Auth::check() ) return Redirect::to('homeAdmin');
//return View::make('homeLogin');
return View::make('homeLogin');
}
// Other methods, store, destroy...
}
I have my routes set like this (routes.php):
<?php
// Home page as guest displays a login form
Route::get('/', ['as' => 'homeLogin', 'uses' => 'SessionsController#create']);
// Authentication via the SessionsControlle
Route::resource('sessions', 'SessionsController');
// Pages for logged in users
Route::group(['before' => 'auth'], function()
{
// Home page with admin panel for authenticated users
Route::get('/', ['as' => 'homeAdmin']);
// Other pages from admin panel
Route::get('manageThis', ['as' => 'manageThis']);
Route::get('manageThat', ['as' => 'manageThat']);
});
And the filters are unchanged, ie (filters.php):
<?php
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
The thing is that I am constantly redirected to '/login' instead of to the 'homeLogin' route. I guess there is something to change in the guest filter but when I edited it, it got even worse and didn't solve the issue.
Have you tried putting homeLogin within a guest group? So like...
Route::group(['before' => 'guest'], function()
{
Route::get('/', ['as' => 'homeLogin', 'uses' => 'SessionsController#create']);
});
Otherwise you can manually check this in your controller/route programatically:
if(!Auth::user()) {
return View::make('guest.page');
}
For further info, check this answer also: Laravel 4: Two different view pages for a single URI based on auth status
Route should be one and programatically check on controller for both login view and dashboard view.You have two routes for this process.
Route::get('/', ['as' => 'homeLogin', 'uses' => 'SessionsController#create']);
Route::get('/', ['as' => 'homeAdmin']);
Delete one and check it on controller like this:
if(Auth::user()) {
return View::make('dashboard')->with('datas', $yourDatabaseQureiesForDashboard);
}
else
{
return View::make('login');
}

Resources