【问题标题】:redirect too many times in laravel在laravel中重定向太多次
【发布时间】:2020-04-28 07:03:10
【问题描述】:

当我进入我的 /home 路由时,显示此问题重定向页面太多次。 我创建了一个名为 UserRole 的自定义中间件。在这个中间件中我设置了一个条件,如果 role==1 然后转到 root(/) 路由,否则转到 /home 路由。第一个条件正常工作,但其他条件抛出这个问题 重定向页面太多次。 我的代码如下:

web.php
Route::get('/', 'FrontendController@FrontPage');
Route::get('/home', 'HomeController@dashboard');

Kernel.php

'user_role' => \App\Http\Middleware\UserRole::class,


UserRole.php(midleware)

public function handle($request, Closure $next)
{
    if(Auth::user()->role == 1){
        return redirect('/');
    }
    else{
        return redirect('/home');
    }
}

Homecontroller.php
  class HomeController extends Controller
 {

 public function __construct()
  {
    $this->middleware('user_role');
  }

 public function dashboard()
  {
    return view('backend.dashboard');
  }
 }

FrontendController.php

class FrontendController extends Controller
{
public function FrontPage(){
    $products=Product::all();
    return view('frontend.main',compact('products'));
}
public function shopPage(){
    $categories=Category::orderBy('name','asc')->get();
    $title='All Product';
    return view('frontend.shop',compact('categories','title'));
 }
}

【问题讨论】:

  • 为什么要使用中间件来处理这个问题?你在使用 laravel auth 脚手架吗?

标签: php laravel redirect


【解决方案1】:

你有一个无限循环。 当您进入 HomeController 时,您会经过中间件。这个中间件将你重定向到 HomeController,控制器调用中间件....

你可以这样改变中间件

public function handle($request, Closure $next)
{
    if(Auth::user()->role == 1){
        return redirect('/');
    }

    return $next($request);
}

此中间件检查您的角色是否为 1。 如果是真的去'/' 如果没有继续

【讨论】:

  • return $next($request);
  • 非常感谢您的回答。现在它可以正常工作了。
猜你喜欢
  • 1970-01-01
  • 2019-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-04
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
相关资源
最近更新 更多