简体   繁体   English

带有POST请求的Laravel路由URL参数

[英]Laravel Routing URL Parameters with POST Request

If I have a route like the following. 如果我有一条类似以下的路线。

Route::post('/user/{id}', 'UserController@my_function');

How do I set up the controller function to be like this so I can use the URL parameter and POST request body data? 如何将控制器功能设置为这样,以便可以使用URL参数和POST请求正文数据? I'd expect it to be similar to the below code, but is this correct? 我希望它类似于下面的代码,但这是正确的吗?

public function my_function($id, Request $request){}

The way you doing is correct according to the laravel docs. 根据laravel文档,您的操作方式是正确的。

If your controller method is also expecting input from a route parameter, list your route arguments after your other dependencies. 如果您的控制器方法也希望从route参数输入,请在其他依赖项之后列出您的route参数。 For example, if your route is defined like so: 例如,如果您的路线是这样定义的:

 Route::put('user/{id}', 'UserController@update');

You may still type-hint the Illuminate\\Http\\Request and access your id parameter by defining your controller method as follows: 您仍然可以键入Illuminate \\ Http \\ Request并通过定义如下所示的控制器方法来访问id参数:

Here is a example using the data you send it: 这是使用您发送的数据的示例:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Update the given user.
     *
     * @param  Request  $request
     * @param  string  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
       $request->all() // here you're acessing all the data you send it
       $user = User::find($id) // here you're getting the correspondent user from the id you send it

    }
}

For more info: docs 有关更多信息: 文档

its ok but i love passing the id like this when i am returning a view 可以,但是我喜欢在返回视图时像这样传递id

public function my_function(Request $request){
return view('myfile',['id'=>$id]);
}

When ever you expose your url arguments like that you have to use a get request parameter to pass it through eg localhost:3000/user/1 每当您公开这样的url参数时,都必须使用get request参数将其传递给例如localhost:3000 / user / 1

Route::get('/user/{id}', 'UserController@my_function');

public function my_function($id){ //do something }

But if you pass an id under the hold ie hidden through post. 但是,如果您在保留下传递ID,即通过帖子隐藏。

Route::post('/user', 'UserController@my_function');

public function my_function(Request $request){ // do something $request->id }

Maybe this is what you wanted to do 也许这就是你想做的

Route::put('user/{id}', 'UserController@my_function');

public function my_function($id){ //do something }

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

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