简体   繁体   English

Laravel 5.4路线请求和参数

[英]Laravel 5.4 Route with Request and Params

I found myself stuck or lost in docs! 我发现自己陷入困境或迷失在文档中!

I'm using Laravel 5.4 and I'm trying to create validation in a controller which requires a request object. 我正在使用Laravel 5.4我正在尝试在需要请求对象的控制器中创建验证

My problem is my route passes parameters, I can't find in the docs an example how you include the Request $request argument and the $id parameter in a Controller method. 我的问题是我的路由传递参数,我在文档中找不到如何在Controller方法中包含Request $request参数和$id参数的示例。

Here is my example: 这是我的例子:

1: SomeController.php 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 with a Paramter in -- routes/web.php 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? 在他们的示例@ https://laravel.com/docs/5.4/requests#accessing-the-request中,他们在其控制器中有Request $request但Route参数会发生什么? :

public function store(Request $request) {}

Question: Do I need to edit the route or is the first parameter ignored if its a request? 问题:我是否需要编辑路径,或者如果是请求,是否会忽略第一个参数?


A: Or would I do this in **SomeController.php ?** A:或者我会在** 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: Perhaps, something like this?: B:也许,这样的事情?:

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

Any advice would help, or even an example! 任何建议都会有所帮助,甚至是一个例子!

Doing

public function edit(Request $request, $id)

should match the route you already have. 应该与您已有的路线相匹配。 So it's ok to do that. 所以这样做是可以的。 Request $request here is not a required parameter that you pass. 此处的Request $request不是您传递的必需参数。 Laravel will take care of it. Laravel会照顾它。

It works this way because everytime you send a request, well Laravel 'sends' a request for you (GET, POST). 它的工作方式是这样的,因为每次发送请求时,Laravel都会向你发送一个请求(GET,POST)。 So, it always exist. 所以,它总是存在的。 But you can use use it within your controller if you dont pass it to the controller function as a parameter. 但是,如果您不将其作为参数传递给控制器​​功能,则可以在控制器中使用它。

However, you can access it through the global helper function request() if you dont want to pass it as a function parameter. 但是,如果您不想将其作为函数参数传递,则可以通过全局帮助函数request()访问它。

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

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

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