【问题标题】:laravel route undefined url to particular controllerlaravel 将未定义的 url 路由到特定的控制器
【发布时间】:2017-02-22 16:39:51
【问题描述】:

在 laravel 5.2 中,我想将所有未定义的 url 路由到一个特定的控制器。

我正在开发类似 CMS 的功能,我想要这个东西。

Route::get('profile', 'Controller@profile');
Route::get('{any}', 'Controller@page');

这样的网址

www.domain.com/post/po-t/some/thing

www.domain.com/profile

所以第一个网址应该重定向到页面功能,第二个网址应该重定向到配置文件功能

基本上我想了解 N 数或参数,因为在页面中它可以是任意数量的参数,例如“www.domain.com/post/po-t/some/thing”

【问题讨论】:

  • 你到底想在Controller@page方法中做什么?

标签: php laravel laravel-5 laravel-5.2


【解决方案1】:

路线

Route::get('{any}', 'Controller@page');

只适用于像

这样的网址

www.domain.com/post

如果你想要它有更多的选择,你必须做另一条路线,比如

Route::get('{any}/{any1}', 'Controller@page');

这将适用于像这个回调这样的两个选项

www.domain.com/post/asdfgd

【讨论】:

  • 我知道,但我想要 www.domain.com/post/asdfgd 的解决方案,因为我们不知道什么可以是数字或参数
  • 也许你应该试试可选参数。据我所知,没有你想要的解决方案。可选参数接近解决方案。 Route::get('{a?}/{b?}/{c?}/{d?}/{e?}/{f?}', 'Controller@page');
【解决方案2】:

未定义的路由生成 404 HTTP 状态。您可以在resources/views/errors 上创建一个404.blade.php 页面,放置您想要显示的任何视图。每当发生 404 错误时,它都会将您重定向到该页面。你不需要做任何其他事情,laravel 会在幕后处理剩下的事情。

【讨论】:

    【解决方案3】:

    使用middleware

    在句柄方法中,您可以访问$request 对象。当找不到路由时,重定向到您的后备路由。查看this question获取当前url的选项

    编辑:可以在Laracasts forum 中找到一个实现。发帖人想保护管理员路由:

    public function handle($request, Closure $next)
    {
        $routeName = Route::currentRouteName();
    
        // isAdminName would be a quick check. For example,
        // you can check if the string starts with 'admin.'
        if ($this->isAdminName($routeName))
        {
            // If so, he's already accessing an admin path,
            // Just send him on his merry way.
            return $next($request);
        }
    
        // Otherwise, get the admin route name based on the current route name.
        $adminRouteName = 'admin.' . $routeName;
    
        // If that route exists, redirect him there.
        if (Route::has($adminRouteName))
        {
            return redirect()->route($adminRouteName);
        }
    
        // Otherwise, redirect him to the admin home page.
        return redirect('/admin');
    }
    

    【讨论】:

      猜你喜欢
      • 2016-07-18
      • 2017-06-09
      • 2018-09-14
      • 1970-01-01
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多