gpt4 book ai didi

php - 带有请求和参数的 Laravel 5.4 路由

转载 作者:可可西里 更新时间:2023-11-01 13:38:23 27 4
gpt4 key购买 nike

我发现自己陷入或迷失在文档中!

我正在使用 Laravel 5.4 并且我正在尝试在需要请求对象的 Controller 中创建验证

我的问题是我的路由传递参数,我在文档中找不到如何在 Controller 方法。

这是我的例子:

1: SomeController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
...
public function edit($id) {
$request = Request; // <-- Do I use that instead of passing an arg?
}

2: 带有参数的路由 -- routes/web.php

Route::match(['GET', 'POST'], '/some/edit/{id}', 'SomeController@edit');

In their example @ https://laravel.com/docs/5.4/requests#accessing-the-request they have Request $request this in their controller, but what happens to Route parameters?:

public function store(Request $request) {}

问题:我需要编辑路由吗?如果是请求,第一个参数是否会被忽略?


答:或者我会在 **SomeController.php 中这样做吗?**

public function edit(Request $request, $id)
{
// I would get the $request, but what happens to $id?
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
]);
}

B:也许,像这样?

public function edit($id)
{
// Or Request::getInstance()?
$this->validate(Request, [
'title' => 'required|unique:posts|max:255',
]);
}

任何建议都会有所帮助,甚至是一个例子!

最佳答案

public function edit(Request $request, $id)

应该匹配你已有的路线。所以这样做是可以的。 Request $request 此处不是您传递的必需参数。 Laravel 会处理它。

之所以这样工作,是因为每次您发送请求时,Laravel 都会为您“发送”一个请求(GET、POST)。所以,它一直存在。但是如果你不把它作为参数传递给 Controller ​​函数,你可以在你的 Controller 中使用它。

但是,如果您不想将它作为函数参数传递,您可以通过全局辅助函数 request() 访问它。

$request = request();
$name = $request->name; // or
$name = request('name');

关于php - 带有请求和参数的 Laravel 5.4 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42545153/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com