繁体   English   中英

Laravel 路由重定向数据

[英]Laravel route redirecting with data

我有一个看起来像这样的基本路线:

Route::prefix('/group')->group(function () {
    // Some routes here
    Route::prefix('/{uuid}')->group(function () {
        // Some routes here
        Route::get('/user/{id}', 'Controller@preview')->name('view-user')->where('id', '[0-9]+');
    }
}

逻辑是我希望id只是数值。 我现在想做的是,如果该值是非数字的,则声明对此的重定向。 假设id的输入是fs 在那种情况下,我希望它重定向到值为1id

我尝试使用Route:redirect ,但无法正常工作。 它看起来像这样:

Route::redirect('/group/{uuid}/user/{id}', '/group/{uuid}/user/1')->where('id', '[^0-9]+');

我更愿意将重定向放在组内,但如果这是唯一的方法,它也可以放在组外。 任何帮助将不胜感激。

发生的事情是,如果我声明了路由重定向,我会收到 404 错误。

编辑:我想在routes/web.php文件中进行。 我知道如何在控制器中执行此操作,但在当前情况下这不是我所需要的。 闭包也不是一种选择,因为那样会阻止路由缓存。

你宣布它倒置了。

在 Laravel 中,您可以通过以下方式重定向传递的参数:

您可以传递名称而不是 url 并简单地传递变量。

Redirect::route('view-user', [$uuid, $id])

我认为您可以在路由器的控制器内部执行此操作,逻辑如下:

class Controller {
    // previous code ..

    public function preview($uuid, $id) {
        if(! is_numeric($id))
            return redirect("/my-url/1");

        // run the code below if $id is a numeric value..
        // if not, return to some url with the id = 1
    }
}

我认为没有办法覆盖 laravel 的“where”功能,但我想在路由绑定中有类似的东西:

或者,您可以覆盖 Eloquent 模型上的 resolveRouteBinding 方法。 此方法将接收 URI 段的值,并应返回应注入路由的类的实例:

/**
 * Retrieve the model for a bound value.
 *
 * @param  mixed  $value
 * @return \Illuminate\Database\Eloquent\Model|null
 */
public function resolveRouteBinding($value)
{
    return $this->where('name', $value)->first() ?? abort(404);
}

但这要求您管理 consise 模型的值而不是您想要的任何 id。

跟进评论

您可以在 routes/web.php 文件中创建一个路由来捕获非数字 ID,并将其重定向到 id=1 的“view-user”

它看起来像这样

Route::get('/group/{uuid}/user/{id}', function ($uuid, $id) {
  return redirect('view-user', ['uuid' => $uuid, 'id' => 1]);
})->where('id', '[^0-9]+');

// and then below have your normal route

Route::get('/group/{uuid}/user/{id}', 'Controller@preview')->name('view-user')->where('id', '[0-9]+');

更新

在您评论说您不想使用闭包之后。

将“错误的输入路径”更改为

Route::get('/group/{uuid}/user/{id}', 'Controller@redirectBadInput')->where('id', '[^0-9]+');

然后在类Controller中添加方法:

public function redirectBadInput ($uuid, $id) {
  return redirect('view-user', ['uuid' => $uuid, 'id' => 1]);
}

您可以在此 SO 线程中看到有关重定向和缓存的更多信息。

像这样在路线中分配路线名称。

return Redirect::route('view-user', ['uuid'=>$uuid,'id'=>$id]);

然后在 web.php 文件中如你所愿。

Route::get('/group/{uuid}/user/{id}', function($uuid, $id){
    echo $uuid;
    echo $id;
})->name('view-user')->where('id', '[0-9]+');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM