Zac
Zac

Reputation: 2081

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

Upvotes: 1

Views: 9663

Answers (3)

rapulu
rapulu

Reputation: 160

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 }

Upvotes: 1

Piazzi
Piazzi

Reputation: 2636

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

Upvotes: 7

Emeka Okafor
Emeka Okafor

Reputation: 457

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

Upvotes: 0

Related Questions