When I try to redirect to the file I need, it displays an error that the Admin class does not exist, how to fix it?
Auth::routes();
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
if (Auth::user()->role == 'Admin')
return redirect('admin');
elseif (Auth::user()->role == 'User')
return redirect('user');
else
return redirect('error');
});
Route::get('error', function () {
return "Sorry, you are unauthorized to access this page.";
});
Route::group(['prefix' => 'admin', 'middleware' => 'admin'], function () {
Route::view('/', 'role.admin');
});
Route::group(['prefix' => 'user', 'middleware' => 'user'], function () {
Route::view('/', 'role.user');
});
});
After creating middleware you need to register it in app/http/Kernel.php file in protected $routeMiddleware array. Then you can use this middleware in your routes(web.php/api.php):
protected $routeMiddleware = [
'admin' => 'App\Http\Middleware\Admin',
];
Related
In my web.php has
Route::post('/user/logout', function () {
Auth::logout();
return redirect()->route('login');
})->name('user-logout');
Auth::routes();
Route::group(
[
'prefix' => LaravelLocalization::setLocale(),
'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath']
], function(){
Route::get('/','SiteController#index')->name('site.index');
Route::group(['prefix' => 'admin'], function () {
Route::get('/', 'AdminController#index')->name('admin.index');
Route::prefix('users')->group(function () {
Route::get('/', 'AdminControllers\UserController#index')->name('admin.users.index');
Route::get('/create', 'AdminControllers\UserController#create')->name('admin.users.create');
Route::post('/store', 'AdminControllers\UserController#store')->name('admin.users.store');
Route::get('/show/{id}', 'AdminControllers\UserController#show')->name('admin.users.show');
Route::get('/edit/{id}', 'AdminControllers\UserController#edit')->name('admin.users.edit');
Route::put('/update/{id}', 'AdminControllers\UserController#update')->name('admin.users.update');
Route::delete('/destroy/{id}', 'AdminControllers\UserController#destroy')->name('admin.users.destroy');
});
});
});
when I try to login with this url
http://dev.practice.uz/
or with this url
http://dev.practice.uz/admin
I go to the same login blade and the same route, I should do separately route and login.blade , Can you give Advise me??
I have two two middlewares. One is admin and another is teacher. In admin, will access all the created url and teacher will get only 2 or 3 url.
Here is my route
Route::group(['middleware' => ['adminAuth']], function () {
Route::get('dashboard', array('as' =>'Teacher Dashboard', 'uses' => 'UserController#dashBoard'));
Route::get('users/profile/edit/{id}', array('as' => 'User Profile Update', 'uses' => 'UserController#userProfile'));
Route::post('users/profile/update/{id}', array('as' => 'User Profile Update', 'uses' => 'UserController#updateUserProfile'));
Route::get('student/leave/application', array('as' => 'Student Leave Application', 'uses' =>'LeaveApplicationController#studentLeaveApplicationList'));
Route::get('leave/application/student/create', array('as' => 'Student Leave Application', 'uses' =>'LeaveApplicationController#studentLeaveApplicationCreate'));
Route::post('leave/student/application/store', array('as' => 'Student Leave Application', 'uses' =>'LeaveApplicationController#studentLeaveApplicationStore'));
Route::get('leave/student/application/categories', array('as' => 'Student Leave Application Categories', 'uses' => 'LeaveApplicationController#studentLeaveCategories'));
});
Route::group(['middleware' => ['teacherAuth']], function () {
Route::get('teacher/dashboard', array('as' =>'Teacher Dashboard', 'uses' => 'UserController#teacherDashBoard'));
Route::get('users/profile/edit/{id}', array('as' => 'User Profile Update', 'uses' => 'UserController#userProfile'));
Route::post('users/profile/update/{id}', array('as' => 'User Profile Update', 'uses' => 'UserController#updateUserProfile'));
});
I want to update each user profile from both middleware. it is working fine when i use profile update url for anyone middleware but when i use profile update url in both middleware then it not wokring just redirect to another url
Here is my middlewares logic
For Admin,Middleware/AdminAuth.php
public function handle($request, Closure $next)
{
$role = User::getUserById(Auth::id());
if(!(\Auth::check()) || ($role->role_name != "admin"))
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
} else {
\Session::flash('errormessage','Invalid Request');
\Session::put('pre_login_url',\URL::current());
return redirect()->guest('/auth/login');
}
}
return $next($request);
}
For Teacher, Middleware/TeacherAuth.php
public function handle($request, Closure $next)
{
$role = User::getUserById(Auth::id());
if(!(\Auth::check()) || ($role->role_name != "teacher"))
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
} else {
\Session::flash('errormessage','Invalid Request');
\Session::put('pre_login_url',\URL::current());
return redirect()->guest('/auth/login');
}
}
return $next($request);
}
Here is my Kernel.php
'adminAuth'=>\App\Http\Middleware\AdminAuth::class,
'teacherAuth'=>\App\Http\Middleware\TeacherAuth::class,
Laravel uses pattern matching for routes and it settles for the first one found. Middlewares don't change route paths so laravel will only recognise the first users/profile/update/{id} route.
You either change the route path so they're not exactly the same, or you go and separate the logic in your controller method. For example, in your UserController::updateUserProfile() method, you can create private methods updateTeacher(), updateAdmin(). So your logic can look like this:
if($role->role_name == "teacher")
{
return $this->updateTeacher();
} else if($role->role_name == "admin")
{
return $this->updateAdmin();
}
Which means you won't need those 2 middlewares. Just apply auth middleware on the route
I'd like to pre check two different Route Groups by the auth:admin middleware. This works perfectly for the first Route Group inside but not for the second which is in an other Namespace.
My Routes file looks like this:
Route::group(['middleware' => ['auth:admin']], function(){
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
});
If I'm not logged in and try to go to admin/dashboard, I'm redirected to login/admin. But if I try to go to team/1/dashboard it says Error 'Trying to get property 'headers' of non-object'.
How can I get the auth:admin Middleware to work with my Team Routes too?
create a middleware
class IsAdmin
{
public function handle($request, Closure $next)
{
if (Auth::user()->permission == 'admin') {
return $next($request);
}
return redirect()->route('some.route'); // If user is not an admin.
}
}
Register in kernel.php
protected $routeMiddleware = [
....
'is.admin' => \App\Http\Middleware\IsAdmin::class,
];
So your routes:
Route::group(['middleware' => 'is.admin'], function () {
Route::group(['prefix' => 'admin', 'namespace' => 'Admin', 'as' => 'admin.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
Route::group(['prefix' => 'team/{team_id}', 'namespace' => 'Team', 'as' => 'team.'], function(){
Route::resource('dashboard', 'DashboardController')->only(['index', 'create', 'store']);
});
});
check app/Http/Controllers/Middleware/RedirectIfAuthenticated.php file and
update the code for different guard use
// app/Http/Controllers/Middleware/RedirectIfAuthenticated.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated
{
public function handle($request, Closure $next, $guard = null)
{
if ($guard == "admin" && Auth::guard($guard)->check()) {
return redirect('/admin');
}
if ($guard == "writer" && Auth::guard($guard)->check()) {
return redirect('/writer');
}
if (Auth::guard($guard)->check()) {
return redirect('/home');
}
return $next($request);
}
}
Trying to play with Laravel today for the first time. I am getting the following error when I attempt to visit:
InvalidArgumentException
Route [dashboard] not defined.
routes/web.php
Route::get('/', ['as' => '/', 'uses' => 'LoginController#getLogin']);
Route::post('/login', ['as' => 'login', 'uses' => 'LoginController#postLogin']);
Route::get('/logout', ['as' => 'logout', 'uses' => 'LoginController#getLogout']);
Route::group(['middleware' => ['authenticate', 'roles']], function (){
Route::get('/dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController#dashboard']);
});
LoginController.php
class LoginController extends Controller
{
use AuthenticatesUsers;
protected $username = 'username';
protected $redirectTo = '/';
protected $guard = 'web';
public function getLogin()
{
if (Auth::guard('web'))
{
return redirect()->route('dashboard');
}
return view('login');
}
public function postLogin(Request $request)
{
$auth = Auth::guard('web')->attempt([
'username' => $request->username,
'password' => $request->password,
'active' => 1]);
if ($auth)
{
return redirect()->route('dashboard');
}
return redirect()->route('/');
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
}
as like name(). You should use one of the two :
Route::group(['middleware' => ['authenticate', 'roles']], function (){
Route::get('/dashboard', 'DashboardController#dashboard')->name('dashboard');
});
Or
Route::group(['middleware' => ['authenticate', 'roles']], function (){
Route::get('/dashboard', [
'as' => 'dashboard',
'uses' => 'DashboardController#dashboard']);
});
After, you clear route cache with php artisan route:clear
Final, you can use php artisan route:list to lists all routes and the action bind
Try this:
Route::get('/dashboard','DashboardController#dashboard')->name('dashboard');
When you use as it names the route , so you have add two name dashbbaorddashboard because you use as and name
Route::group(['middleware' => ['authenticate', 'roles']], function (){
Route::get('/dashboard', ['uses' => 'DashboardController#dashboard'])->name('dashboard');
});
This will work
I have a simple users table which I define and admin by having a 1 in the type column.
I have the following setup in my middleware but this still doesn't stop non admins accessing admin only areas.
Middleware:
<?php
namespace App\Http\Middleware;
use Closure;
class Admin {
public function handle($request, Closure $next)
{
if (Auth::user()->isAdmin())
{
return redirect('home');
}
return $next($request);
}
}
Kernal:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'admin' => App\Http\Middleware\Admin::class,
];
Routes:
Route::group(['middleware' => 'auth', 'admin'], function () {
Route::get('admin/dashboard', 'AdminController#dashboard');
Route::get('admin/orders', 'AdminController#orders');
});
Function in my User class:
public function isAdmin()
{
if (Auth::user()->type == '1')
{
return true;
}
else
{
return false;
}
}
You need to pass multiple middleware as an array:
Route::group(['middleware' => ['auth', 'admin']]