1

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){}

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

When ever you expose your url arguments like that you have to use a get request parameter to pass it through e.g 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 i.e 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 }

1 Comment

Thanks for your response, but your second example is not what I wanted to do but I thank your response
0

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]);
}

1 Comment

That's another way to do it, thank you I may use this method in some occasions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.