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

标签 php laravel

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

我正在使用 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/

相关文章:

php - DateTime倒计时和到期

php - Laravel 5.3 将主页设置为登录屏幕

Laravel HttpException - 没有错误消息

Laravel 5.0 文件夹结构 : public vs. 资源

php - 将函数名称文字传递给高阶函数安全吗?

php - Laravel 5 动态创建 Eloquent 模型

php - 在 Laravel 中通过查询选择计算属性

php - Laravel 请求具有复杂 url 的通配符

php - mysql 和 php PDO - 如果连接意外关闭,未提交的事务会发生什么?

php - 将 DomPDF 作为我的 phpWord pdf 编写器