简体   繁体   中英

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? 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.

If your controller method is also expecting input from a route parameter, list your route arguments after your other dependencies. 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:

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

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

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.

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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