laravel 5.2 how to pass variable to route.php from middleware? - php

i have a middleware, i want it to pass $role to the route.php
public function handle($request, Closure $next)
{
if ($this->auth->check())
{
$role= "normal";
$user_roles = AssignedRoles::join('roles','role_user.role_id','=','roles.id')
->where('user_id', $this->auth->user()->id)->select('roles.is_admin', 'roles.is_vendor')->get();
foreach($user_roles as $item)
{
//var_dump($item->is_vendor);
//die();
if($item->is_admin==1)
{
$role = "admin";
}
if($item->is_vendor==1)
{
$role = "vendor";
}
}
if($role=="normal"){
return $this->response->redirectTo('/');
}
//$request->attributes->add(['admin' => $admin, 'vendor' => $vendor]);
$request->attributes->add(['role' => $role]);
View::share ('role', $role);
return $next($request);
}
return $this->response->redirectTo('/');
}
is there any way to do that?
My route:
Route::group(['prefix' => 'admin', 'middleware' => ['auth']], function() {
Route::auth();
Route::pattern('id', '[0-9]+');
Route::pattern('id2', '[0-9]+');
#Admin Dashboard
Route::get('dashboard', 'Admin\DashboardController#index');
Route::get('vendor/{id}/edit', 'Admin\VendorController#getEdit');
Route::post('vendor/{id}/edit', 'Admin\VendorController#postEdit');
});

You can do something like this:
// In your middleware
$request->offsetSet('role', $role);
Then in the routes.php:
use Illuminate\Http\Request;
Route::get('test', ['middleware' => 'auth', function(Request $request) {
dd($request->get('role'));
}]);

Related

Laravel Custom Middleware: ERR_TOO_MANY_REDIRECTS

I'm using Laravel Breeze + Inertia (React) and want to implement custom auth.
I'm having infinite redirection (ERR_TOO_MANY_REDIRECTS) when visiting /dashboard on this middleware.
Route::get('register', [RegisteredUserController::class, 'create'])
->name('register');
Route::post('register', [RegisteredUserController::class, 'store']);
Route::get('login', [AuthenticatedSessionController::class, 'create'])
->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
Route::middleware(['custom_auth'])->group(function () {
Route::get('/dashboard', function () {
return Inertia::render('Dashboard');
})->name('dashboard');
});
class CustomAuthMiddleware
{
public function handle(Request $request, Closure $next)
{
if (session()->has('user_data')) {
return redirect(RouteServiceProvider::HOME);
}
return $next($request);
}
}
This works:
namespace App\Http\Middleware;
class RedirectIfAuthenticated
{
public function handle(Request $request, Closure $next, ...$guards)
{
if (session()->has('user_data')) {
return redirect()->route('users.index');
}
return $next($request);
}
}
namespace App\Http\Middleware;
class CustomAuthMiddleware
{
public function handle(Request $request, Closure $next)
{
if (session()->has('user_data')) {
return $next($request);
}
return redirect('login');
}
}
Route::middleware('guest')->group(function () {
Route::get('register', [AuthController::class, 'register'])
->name('register');
Route::post('register', [AuthController::class, 'registerPost']);
Route::get('login', [AuthController::class, 'login'])
->name('login');
Route::post('login', [AuthController::class, 'loginPost']);
});
Route::middleware('custom_auth')->group(function () {
Route::get('/', function () { return redirect()->route('users.index'); });
Route::resource('users', UserController::class);
});

Laravel Routing "Route [dashboard] not defined?

I'm trying to config an user/admin environment in my laravel page, and whenever I try group the routes, I'll get one of the mentioned error back. What am I doing wrong? I tried both formats, same error.
web.php
//supposed user dashboard
Route::group(['middleware' => ['auth', 'user']], function () {
Route::get('/dashboard', 'DashboardController#index')->name('dashboard');
});
//supposed admin dashboard
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', [AdminDashController::class, 'index']);
});
eg AdminDashController:
public function index()
{
return view("admin_dashboard");
}
DashboardController does the same, but returning user view.
I'm new to laravel, I appriciate any help!
Update:
I tried the solution below, my result is that I'm now getting "Route [user.dashboard] not defined." error...
My web.php
Route::group(['middleware' => ['auth', 'user']], function () {
Route::get('/dashboard', [UserDashController::class, 'index'])->name('user.dashboard');
});
// admin dashboard
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', [AdminDashController::class, 'index'])->name('admin.dashboard');
});
my AdminDashController and UserDashController:
public function index()
{
return view('user_dashboard');
}
AND
public function index()
{
return view('admin_dashboard');
}
I have a RedirectIfAuthenticated.php
public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
/** #var User $user */
$user = Auth::guard($guard);
// to admin dashboard
if ($user->hasRole('admin')) {
return redirect()->route('admin.dashboard');
}
// to user dashboard
else if ($user->hasRole('user')) {
return redirect(route('user.dashboard'));
}
}
}
return $next($request);
}
Also having an Admin and User redirect:
AdminAuthenticated.php:
public function handle(Request $request, Closure $next)
{
if( Auth::check() )
{
/** #var User $user */
$user = Auth::user();
// if user is not admin take him to his dashboard
if ( $user->hasRole('user') ) {
return redirect()->route('user.dashboard');
}
// allow admin to proceed with request
else if ( $user->hasRole('admin') ) {
return $next($request);
}
}
abort(403); // permission denied error
}
UserAuthenticated
public function handle(Request $request, Closure $next)
{
if( Auth::check() )
{
/** #var User $user */
$user = Auth::user();
// if user is admin take him to his dashboard
if ( $user->hasRole('admin') ) {
return redirect(route('admin.dashboard'));
}
// allow user to proceed with request
else if ( $user->hasRole('user') ) {
return $next($request);
}
}
abort(403); // permission denied error
}
Update 2:
I replaced the routing in web.php as follows:
Route::middleware(['auth','user'])->group(function () {
Route::prefix('user')->group(function () {
Route::get('/dashboard', [UserDashController::class, 'index'])->name('user.dashboard');
});
});
Route::middleware(['auth','admin'])->group(function () {
Route::prefix('admin')->group(function () {
Route::get('/dashboard', [AdminDashController::class, 'index'])->name('admin.dashboard');
});
});
Still same error: "Route [user.dashboard] not defined."
The problem may be in your route name. One route has a named dashboard another was not. Use the below code hope this will resolve your problem
// user dashboard
Route::group(['middleware' => ['auth', 'user']], function () {
Route::get('/dashboard', 'DashboardController#index')->name('user.dashboard');
});
// admin dashboard
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', 'DashboardController#index')->name('admin.dashboard);
})
use the route name in stead of url.
in my case, instead using your code below :
Route::group(['middleware' => ['auth', 'user']], function () {
Route::get('/dashboard', [UserDashController::class, 'index'])->name('user.dashboard');
});
// admin dashboard
Route::group(['middleware' => ['auth', 'admin']], function () {
Route::get('/dashboard', [AdminDashController::class, 'index'])->name('user.dashboard');
});
i use my own code, so define the middleware first and use prefix on it :
Route::middleware(['auth','user'])->group(function () {
Route::prefix('user')->group(function () {
Route::get('/dashboard', [UserDashController::class, 'index'])->name('user.dashboard');
});
});
Route::middleware(['auth','admin'])->group(function () {
Route::prefix('admin')->group(function () {
Route::get('/dashboard', [AdminDashController::class, 'index'])->name('admin.dashboard');
});
});
maybe you should differentiate routing between dashboard for admin and user. you can use like this : /admin/dashboard and /user/dashboard
edit :
i think there's some typo on your code :
// to admin dashboard
if ($user->hasRole('admin')) {
return redirect(route('admin.dashboard'));
}
return redirect route should typed like this : return redirect()->route('admin.dashboard)

Laravel 7 - Redirects to the main page when the optional parameter is empty

I have a route with an optional parameter in web.php:
my web.php: (the route that has the problem is marked with a comment)
Route::middleware(['auth', 'dashboard'])->group(function () {
Route::get('/', 'DashboardController#home')->name('root');
Route::prefix('/drivers')->group(function () {
Route::view('/', 'dashboard.driver.main');
Route::post('/', 'UserController#addDriver');
Route::get('/{id}', function ($id) {
if (Auth::user()->can('view_user')) {
$user = User::find($id);
return view('dashboard.user.view', ['user' => $user]);
}
return view('pages.403');
});
//----------------------------------------
// My route with the problem
// ---------------------------------------
Route::get('/driver-dropdown/{q?}', function ($q=null){
return $q;
})->name('driver.dropdown');
});
});
and it is my dashboard middleware:
public function handle($request, Closure $next)
{
if(!in_array(\Auth::user()->getOriginal('role'), ['superadmin', 'admin', 'supporter']) )
{
return abort(403);
}
return $next($request);
}
When I enter the host-name/drivers/driver-dropdown/jo URL, I get jo
BUT When I enter the host-name/drivers/driver-dropdown/ URL, I will be redirected to the host-name/ that means root route!
Edit: updated web.php
You should reorder your routes like this:
Route::get('/driver-dropdown/{q?}', function ($q=null){
return $q;
})->name('driver.dropdown');
Route::get('/{id}', function ($id) {
if (Auth::user()->can('view_user')) {
$user = User::find($id);
return view('dashboard.user.view', ['user' => $user]);
}
return view('pages.403');
});
Currently, when you go to host-name/drivers/driver-dropdown/, it will match the /{id} route.
If I’m correct the URL’s in your routes which are grouped shouldn’t start with a /, except for the main route of course. I’ve had this issue too.
Should be like this:
Route::middleware(['auth', 'dashboard'])->group(function () {
Route::get('/', 'DashboardController#home')->name('root');
Route::prefix('drivers')->group(function () {
Route::get('driver-dropdown/{q?}', function ($q=null){
return $q;
})->name('driver.dropdown');
});
});

Laravel's 5.5 authentication bouncing back

I'm following a tutorial for login.
I wrote all the code step by step but at the end I am not able to log in, even when I provide the correct credentials.
Below is my code:
LoginController
public function getLogin()
{
if (Auth::guard('web')->check())
{
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()->back()->with(['error' =>'Wrong Credentials']);
}
public function getLogout()
{
Auth::guard('web')->logout();
return redirect()->route('/');
}
DashboardController
public function __construct()
{
$this->middleware('auth');
}
public function dashboard()
{
return view('layouts.app');
}code here
Middleware (VisitorsMiddleware.php)
public function handle($request, Closure $next, $guard = 'web')
{
if(!Auth::guard($guard)->check()){
return redirect()->route('dashboard');
}
return $next($request);
}
CheckRole.php
epublic function handle($request, Closure $next)
{
$roles = $this->getRequiredRoleForRoute($request->route());
if($request->user()->hasRole($roles)|| !$roles)
{
return $next($request);
}
return redirect()->route('/noPermission');
}
private function getRequiredRoleForRoute($route)
{
$actions = $route->getAction();
return isset($actions['roles']) ? $actions['roles']: null;
}
web.php
Route::group(['middleware'=>['visitors','roles']],function (){
Route::get('/logout', ['as' => 'logout', 'uses' => 'LoginController#getLogout']);
Route::get('/dashboard', ['as' => 'dashboard', 'uses' => 'DashboardController#dashboard']);});
Route::get('/', ['as' => '/', 'uses' => 'LoginController#getLogin']);
Route::post('/login', ['as' => 'login', 'uses' => 'LoginController#postLogin']);

Don't working authentication in laravel 5.2

Don't working authentication. I create authentication manually.
My AdminController:
class AdminController extends Controller
{
public function signin() {
return view('admin.signin');
}
public function index(Request $request) {
dd(Auth::check());
if (Auth::check())
return view('admin.index.index', ['login' => Auth::user()->name]);
else
return redirect()->action('AdminController#signin');
}
public function login() {
$data = Input::all();
if (Auth::attempt(['name' => $data['login'], 'password' => $data['password']])) {
return redirect()->intended('/admin');
} else {
return redirect()->intended('/admin/signin');
}
}
public function logout() {
if (Auth::logout() ) {
return Redirect::to('/admin');
}
}
}
My routes.php file:
//GET
Route::get('/', 'IndexController#index');
Route::get('/admin/signin', 'AdminController#signin');
Route::get('/admin', 'AdminController#index');
Route::get('/admin/logout', 'AdminController#logout');
//POST
Route::post('/admin/auth', 'AdminController#login');
dd(Auth::check()); returned false
What I doing wrong?
In Laravel 5.2 you need to define routes using web middleware to make sessions work, so your routes.php file should look like this:
Route::group(['middleware' => ['web']], function () {
//GET
Route::get('/', 'IndexController#index');
Route::get('/admin/signin', 'AdminController#signin');
Route::get('/admin', 'AdminController#index');
Route::get('/admin/logout', 'AdminController#logout');
//POST
Route::post('/admin/auth', 'AdminController#login');
});

Categories