-1

i am trying to make authentication of laravel with middleware but my middleware not working to redicrect to admin/dashboard page my code below have data in data base that roll_as is 1 and i trying to login as admin but when i give input of login credentials of login then middleware redirect me on /home page help me my all code is below
// ths is tha adminMiddleware

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Auth;




class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        
        if(!Auth::user()->roll_as =='1'){
            return redirect('/home')->with('status','Access Denied Becouse  You Are Not Admin This Acces Only  For Admin');
        }
        return $next($request);
    }
}


/// LoginController
<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\App\Http\Middleware\Authenticate;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    // protected $redirectTo = RouteServiceProvider::HOME;
    protected function authenticated()
    {
        if(Auth::user()->roll_as=='1'){
            return redirect('admin/dashboard')->with('status','Welcome Admin');
        }
         else{
             return redirect('/home')->with('status','Welocome You are logged In Succesfully');
         }
    }

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }
}

//web.php
<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Auth;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');

Route::group(['prefix' => 'admin','middleware'=>(['auth','asAdmin'])], function () {
    Route::get('dashboard', [App\Http\Controllers\Admin\DashboardController::class,'index']);
});
//kernal.php

  */
    protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \App\Http\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'asAdmin' => \App\Http\Middleware\AdminMiddleware::class,

    ];

i am trying to make middleware and this middleware not working

please help me

3 Answers3

1

Because the ! operator has a higher precedence than the == operator, the ! operator will happen first. Reference more https://www.php.net/manual/en/language.operators.precedence.php

You can do:

// you can use 1 instead of '1'

if(Auth::user()->roll_as != '1'){
    return redirect('/home')->with('status','Access Denied Becouse  You Are Not Admin This Acces Only  For Admin');
}

Or:

// you can use 1 instead of '1'

if(!(Auth::user()->roll_as == '1')){
    return redirect('/home')->with('status','Access Denied Because  You Are Not Admin This Acces Only  For Admin');
}

Or if Auth::user()->roll_as is an integer type, you can use:

Auth::user()->roll_as !== 1

if Auth::user()->roll_as is a string type, it should be:

Auth::user()->roll_as !== '1'

Reference https://www.php.net/manual/en/language.operators.comparison.php

Khang Tran
  • 2,015
  • 3
  • 7
  • 10
0

I think the condition on your middleware is wrong. The !Auth::user()->roll_as I think it is false so your condition in your middleware is if (false == '1') so it always fails the condition. You should try to remove the ! at the start of the condition and change it to Auth::user()->roll_as !== '1'

xenooooo
  • 1,106
  • 1
  • 2
  • 8
0
first you need to check type of Auth::user()->roll_as;

you can try this also 

if(Auth::user()->roll_as== 1 || Auth::user()->roll_as=='1'){
            return redirect('admin/dashboard')->with('status','Welcome Admin');
        }
         else{
             return redirect('/home')->with('status','Welocome You are logged In Succesfully');
         }