Laravel - add in core/routes/ if username exist - php

Route::middleware('admin')->group(function () {
Route::get('dashboard', 'AdminController#dashboard')->name('dashboard');
Route::get('profile', 'AdminController#profile')->name('profile');
Route::post('profile', 'AdminController#profileUpdate')->name('profile.update');
Route::get('password', 'AdminController#password')->name('password');
Route::post('password', 'AdminController#passwordUpdate')->name('password.update');
I have this code in routes and I want to add "if username == "staff"
Route::get('dashboard', 'AdminController#dashboard')->name('dashboard');
not others pages.

First create StaffMiddleware.php in following path app/Http/Middleware/StaffMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class StaffMiddleware
{
/**
* Handle an incoming request. User must be logged in to do admin check
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::user()->username == 'staff')
{
return $next($request);
}
return redirect()->guest('/');
}
}
In app/Http/Kernel.php add the following line
protected $routeMiddleware = [
// your existing code
'staff' => \App\Http\Middleware\StaffMiddleware::class,
];
Rewrite the following route
Route::get('dashboard', 'AdminController#dashboard')->name('dashboard');
TO
Route::get('dashboard', 'AdminController#dashboard')->name('dashboard')->middleware('staff');
Now whenever you want to check this condition you just need to add ->middleware('staff') in route.

Related

How can I add role in the route?

Here is my current route: (which works as well)
Route::get('/register', ['uses' => 'registerController#form','as'=>'register','middleware' => 'roles', 'roles' => ['admin'] ]);
Now I want to know, how can I use role when I write the middleware like ->middleware('role') ?
Note: This doesn't work:
Route::get('/register', 'registerController#form')->name('register')->middleware('role')->role(['admin']);
Route::get('/register', 'registerController#form')->name('register')->middleware('role:admin');
i guess you wanted this
for multiple
Route::group(['middleware' => ['role:Normal_User,Admin']], function() {
Route::get('/register', 'registerController#form');
});
Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a :. Multiple parameters should be delimited by commas.
You can make your own middleware:
<?php
namespace App\Http\Middleware;
use Closure;
class CheckRole
{
/**
* Handle the incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #param string $role
* #return mixed
*/
public function handle($request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
// Redirect...
}
return $next($request);
}
}
And call it like this:
Route::get('/register', 'registerController#form')->name('register')->middleware('role:editor');
Source: https://laravel.com/docs/5.4/middleware#middleware-parameters

laravel constructor redirect

I have a method for checking if a user's role is an admin, if not, redirect them with return redirect('/')->send();. How can I check for user role and redirect the user without displaying the page and waiting for a redirect?
My Controller:
class AdminController extends Controller
{
public function __construct()
{
if (Auth::check())
{
$user = Auth::user();
if ($user->role != 'admin')
{
return redirect('/')->send();
}
}
else
{
return redirect('/')->send();
}
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return View('admin/index');
}
}
Create your own Middleware. Here is an example. In my example, I have several usergroups in a separate model. You have to change the code for your needs.
Create the Middleware via terminal/console:
php artisan make:middleware UserGroupMiddleware
The created middleware class could be find in app/Http/Middleware/UserGroupMiddleware.php
You need the following code in your middleware:
namespace App\Http\Middleware;
use Closure;
use App\User;
use App\Usergroup;
class UserGroupMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $group)
{
if($request->user() !== NULL){
$userGroupId = $request->user()->group;
$userGroup = Usergroup::find($userGroupId);
if($userGroup->slug === $group){
return $next($request);
}
}
// Redirect the user to the loginpage
return redirect('/login');
}
}
Now you have to register this middleware in app/Http/Kernel.php:
protected $routeMiddleware = [
// other middlewares
// Custom Middleware
'group' => \App\Http\Middleware\UserGroupMiddleware::class
];
Finally you need to attach the middleware to your route:
Route::group(['middleware' => 'group:admin'], function(){
// Routes for admins, e.g.
Route::get('/dashboard', 'SomeController#dashboard');
});
// Or for a single route:
Route::get('/dashboard', ['middleware' => 'group:admin'], function(){
return view('adminbereich.dashboard');
});
Remember, that you could pass in multiple middlewares with:
Route::get('/some/route', ['middleware' => ['group:admin', 'auth']], 'SomeController#methodXYZ');
import redirect by adding this to the above the class
use Illuminate\Support\Facades\Redirect;
And the make your redirect by using
return Redirect::to('login');

Is there anyway to code such that I can define or condition in middleware?

I have three roles in my application. I have a condition in which two roles can access same page. For that I write below code.
in below code, sub plan1 and sub plan 2 are roles.
Route::group(['middleware' => ['web', 'auth', 'SubPlan1', 'SubPlan2']], function () {
Route::get('/Parent-1-Info', '\ContactInfoController#Parent1Info'));
});
if sub plan1, tries to access the page, I get 404 error because i mentioned both middleware in same group.
Is there anyway to code such that I can define or condition in middleware?
For role based authentication I'm using this middleware:
namespace App\Http\Middleware;
use Auth;
use Closure;
use App\Role;
use Illuminate\Support\Collection;
class RoleMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next, $roles = null, $guard = null)
{
$roles = Role::whereIn('slug', explode('|', $roles))->get();
if (! Auth::guard($guard)->user()->hasRole($roles)) {
return abort(403, 'Forbidden');
}
return $next($request);
}
}
Then register the middleware in Kernel.php
'role' => \App\Http\Middleware\RoleMiddleware::class,
On the user model make sure you have a method to check if user has a set of roles, example:
public function hasRole($role)
{
if (is_int($role)) {
return $this->roles->contains('id', $role);
}
if (is_string($role)) {
return $this->roles->contains('slug', $role);
}
if ($role instanceof Model) {
return $this->roles->contains('id', $role->id);
}
return !! $role->intersect($this->roles)->count();
}
And you can use the middleware like this:
Route::group(['middleware' => ['auth', 'role:admin|staff'], ...);
You can replace admin|staff with your role names, separated by |. If you want to add custom guard then you can pass it as second parameter role:admin|staff,mycustomguard

Laravel 5 middleware error

I keep getting an error every time I use myroute middleware. Below is the middleware class. its currently empty.
<?php
namespace App\Http\Middleware;
use Closure;
class EnforceHttps
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
When I attach it to my route like so it gives me an error.
Route::get('/', ['middleware' =>'https',function () {
//Route::get('/', function () {
return view('launch');
}]);
If I uncomment the line below which does not include the middleware instead all is good. Why is this?

laravel middleware not working as expected

I have created two middleware in order to protect user route and admin routes
my UserMiddleware looks like this
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
class UserMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->hasRole('user')) {
return $next($request);
}
throw new \Exception("Unauthorized");
}
}
and this is my Adminmiddleware
<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use App\Role;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (Auth::user()->hasRole('admin')) {
return $next($request);
}
throw new \Exception("Unauthorized");
}
}
Now what i want is when admin is logging in, i want a admin dashboard to open and when user is logging in, i want user dashboard to open, but now, it is redirecting me only to the admin route only when I try to login from user and admin, I have my user protected routes like this
Route::group(['middleware' => 'auth', 'user'], function () {
//all user routes
});
and admin protected routes
Route::group(['middleware' => 'auth', 'admin'], function () {
//all admin routes
});
and in my kernel.php, I have also added
'admin' => \App\Http\Middleware\AdminMiddleware::class,
'user' => \App\Http\Middleware\UserMiddleware::class,
and this is how I have validated a login in my controller
$loginData = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'confirmed' => 1
);
/*
* Checking against the record in database whether the email and password is valid
* Or the record exists in the database
*/
if (Auth::validate($loginData)) {
if (Auth::attempt($loginData)) {
return Redirect::intended('dashboard');
}
}
else {
// if any error send back with message.
Session::flash('error', 'Invalid Email/Password Combination');
return Redirect::to('login');
}
how can I make my middleware work and show admin dashboard when admin logs and user dashboard when user logs in. This has created a big problem for me.
First of all, if you want to show unauthorized users the login form, your middleware should redirect to login form. In order to have it, replace
throw new \Exception("Unauthorized");
with
return redirect(route('login'));
Secondly, your login controller should redirect users to the dashboard corresponding to their roles. In order to get the proper redirect, replace
if (Auth::attempt($loginData)) {
return Redirect::intended('dashboard');
}
with
if (Auth::attempt($loginData)) {
return Redirect::intended(Auth::user()->hasRole('admin') ? 'admin_dashboard' : 'user_dashboard');
}
The last issue is that you apply middleware to your routes incorrectly. If you want to apply multiple middlewares, you need to pass a list as middleware paramter. Replace
['middleware' => 'auth', 'user']
with
['middleware' => ['auth', 'user']]

Categories